如何调用包含完成处理程序的函数?
How do I call my function that contains a completion handler?
仍在尝试掌握完成处理程序的窍门,因为我的大部分应用程序都使用异步的剩余 api 调用。我的项目使用 Alamofire
和 SwiftyJSON
我有一个 class 函数接受我想用来调用我的 POST
api 并将值插入数据库的参数. API returns 插入的新行的 ID。我想从函数中获取 JSON
对象 return 的响应。这是函数:
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: ???)
}
编辑:更新了现在的功能。完成后不能return任何东西:
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!))
}
}
您需要设置完成处理程序的类型。你似乎有一个 JSON 类型的参数,所以像这样
completionHandler: (JSON) -> Void
要使其成为可选的,您可以这样做
completionHandler: ((JSON) -> Void)?
然后你会像这样打电话
Inventory.insertItem("NewFromFunc", description: "new function!!!", quantityOnHand: 400, reorderPoint: 1, supplier_id: 2){ data in
//Do something with the data object
}
如果您要拥有多个具有相同类型处理程序等的方法,也可以通过创建 typeAlias 来实现
这是我如何在我的休息客户端 class 中使用类型别名的示例,因为响应用于多种方法
typealias ServiceResponse = (JSON, NSError?) -> Void
class RESTClient : NSObject {
static let sharedInstance = RESTClient()
func makeRequest(type: String, endPoint: String, parameters: [String: AnyObject]?, onCompletion: ServiceResponse){
makeRequest(type, endPoint: endPoint, parameters: parameters, files: nil, onCompletion: onCompletion)
}
...
您可以创建一个新的 class
导入 UIKit
typealias ServiceResponse = (NSDictionary!, NSError!) -> Void
class AFNinjector: NSObject {
func getDataWith(parameters:NSDictionary, url:String, onCompletion: ServiceResponse) -> Void {
let manager:AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
let serializer:AFJSONRequestSerializer = AFJSONRequestSerializer()
manager.responseSerializer.acceptableContentTypes = NSSet(objects:"text/html") as NSSet as Set<NSObject>
manager.requestSerializer = serializer
manager.POST(url, parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responsobject: AnyObject?) -> Void in
let data = responsobject as! NSDictionary?
onCompletion(data,nil)
}) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
let errorObject = error as NSError?
onCompletion(nil,errorObject)
}
}
}
之后你可以调用这个
let Obj=AFNInjector()
let parameters:NSDictionary = ["apicall":"Login","password":txtPassword.text,"email":txtEmail.text]
Obj.getDataWith(parameters, url:BASEURL) { (result, error) -> Void in
if (result != nil){
print(result)
}
else{
}
}
仍在尝试掌握完成处理程序的窍门,因为我的大部分应用程序都使用异步的剩余 api 调用。我的项目使用 Alamofire
和 SwiftyJSON
我有一个 class 函数接受我想用来调用我的 POST
api 并将值插入数据库的参数. API returns 插入的新行的 ID。我想从函数中获取 JSON
对象 return 的响应。这是函数:
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: ???)
}
编辑:更新了现在的功能。完成后不能return任何东西:
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!))
}
}
您需要设置完成处理程序的类型。你似乎有一个 JSON 类型的参数,所以像这样
completionHandler: (JSON) -> Void
要使其成为可选的,您可以这样做
completionHandler: ((JSON) -> Void)?
然后你会像这样打电话
Inventory.insertItem("NewFromFunc", description: "new function!!!", quantityOnHand: 400, reorderPoint: 1, supplier_id: 2){ data in
//Do something with the data object
}
如果您要拥有多个具有相同类型处理程序等的方法,也可以通过创建 typeAlias 来实现
这是我如何在我的休息客户端 class 中使用类型别名的示例,因为响应用于多种方法
typealias ServiceResponse = (JSON, NSError?) -> Void
class RESTClient : NSObject {
static let sharedInstance = RESTClient()
func makeRequest(type: String, endPoint: String, parameters: [String: AnyObject]?, onCompletion: ServiceResponse){
makeRequest(type, endPoint: endPoint, parameters: parameters, files: nil, onCompletion: onCompletion)
}
...
您可以创建一个新的 class
导入 UIKit
typealias ServiceResponse = (NSDictionary!, NSError!) -> Void
class AFNinjector: NSObject {
func getDataWith(parameters:NSDictionary, url:String, onCompletion: ServiceResponse) -> Void {
let manager:AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
let serializer:AFJSONRequestSerializer = AFJSONRequestSerializer()
manager.responseSerializer.acceptableContentTypes = NSSet(objects:"text/html") as NSSet as Set<NSObject>
manager.requestSerializer = serializer
manager.POST(url, parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responsobject: AnyObject?) -> Void in
let data = responsobject as! NSDictionary?
onCompletion(data,nil)
}) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
let errorObject = error as NSError?
onCompletion(nil,errorObject)
}
}
}
之后你可以调用这个
let Obj=AFNInjector()
let parameters:NSDictionary = ["apicall":"Login","password":txtPassword.text,"email":txtEmail.text]
Obj.getDataWith(parameters, url:BASEURL) { (result, error) -> Void in
if (result != nil){
print(result)
}
else{
}
}