【发布时间】:2016-02-23 18:28:00
【问题描述】:
由于我的大多数应用程序都使用异步的 rest api 调用,因此仍在尝试掌握完成处理程序的窍门。我的项目使用Alamofire 和SwiftyJSON 我有一个类函数,它接受我想用来调用我的POST api 并将值插入数据库的参数。 API 返回插入的新行的 ID。我想将响应作为从函数返回的 swifty JSON 对象。这是函数:
class func insertItem(item: String, description: String, quantityOnHand: Int, reorderPoint: Int, supplier_id:Int, completionHandler: JSON -> Void) {
let urlEndpoint = Constants.Urls.Inventory.Add
let newItem = ["item": item, "description": description, "quantityOnHand": quantityOnHand, "reorderPoint": reorderPoint, "supplier_id": supplier_id]
Alamofire.request(.POST, urlEndpoint, parameters: (newItem as! [String : AnyObject]), encoding: .JSON)
.responseJSON { response in
guard response.result.error == nil else {
//got an error, need to handle it
print(response.result.error!)
return
}
completionHandler(JSON(response.response!))
}
}
我正在尝试调用此函数,但我不确定为完成参数添加什么:
Inventory.insertItem("NewFromFunc", description: "new function!!!", quantityOnHand: 400, reorderPoint: 1, supplier_id: 2, completionHandler: ???)
}
编辑:更新了现在的功能。完成后无法返回任何内容:
func insertItem(item: String, description: String, quantityOnHand: Int, reorderPoint: Int, supplier_id:Int, completionHandler: (JSON) -> Void) {
let urlEndpoint = "http://url"
let newItem = ["item": item, "description": description, "quantityOnHand": quantityOnHand, "reorderPoint": reorderPoint, "supplier_id": supplier_id]
Alamofire.request(.POST, urlEndpoint, parameters: ((newItem) as! [String : AnyObject]))
.responseJSON { response in
//print(newItem)
guard response.result.error == nil else {
//got an error, need to handle it
print("Error thread")
return
}
if let value: AnyObject = response.result.value {
//hande results as JSON without bunch of nested if loops
let statusCode = response.response?.statusCode
if statusCode == 201 {
//let newid = value["id"]
//let status = value["status"]
print("Status is 201")
print(value)
}
else {
print("there's an issue returning data")
}
}
completionHandler(JSON(response.response!))
}
}
【问题讨论】:
标签: swift2 alamofire swifty-json