我在Swift 3中编写了以下方法
func postFormData(url : String, parameters: Parameters!, headers : HTTPHeaders!, completionHandler : (response : Any, error: Any)) {
Alamofire.request(url, method : .post, parameters: parameters, headers: headers)
.responseJSON { response in
if let status = response.response?.statusCode {
switch(status)
{
let data = result as! NSDictionary
case 200:
if let result = response.result.value {
completionHandler(data)
}
default:
completionHandler(nil, data)
}
}
}
}
completionHandler(data)
陈述Cannot call value of non-function type '(response: Any, error Any)'
completionHandler(nil, data)
来处理错误是最佳做法吗? PS:我是iOS
和Swift 3
答案 0 :(得分:2)
您错过了completionHandler
-> Void
和参数名称的返回,我在此处添加了默认值_
:
func postFormData(url : String, parameters: Parameters!, headers : HTTPHeaders!, completionHandler : (_ response : Any, _ error: Any) -> Void ) {
Alamofire.request(url, method : .post, parameters: parameters, headers: headers)
.responseJSON { response in
if let status = response.response?.statusCode {
switch(status)
{
let data = result as! NSDictionary
case 200:
if let result = response.result.value {
completionHandler(data)
}
default:
completionHandler(nil, data)
}
}
}
}
对于错误部分,我会添加onError
as,onError: (NSError) -> Void)
并在发生错误时返回onError。像这样:
func postFormData(url : String, parameters: Parameters!, headers : HTTPHeaders!, completionHandler : (_ response : Any, _ error: Any) -> Void, onError: (NSError) -> Void)
答案 1 :(得分:-1)
使用以下函数Swift 3:
func postFormData(url : String, parameters: Parameters!, headers : HTTPHeaders!, completionHandler : (_ response : Any?, _ error: Any?)-> Void) {
Alamofire.request(url, method : .post, parameters: parameters, headers: headers)
.responseJSON { response in
if let status = response.response?.statusCode {
switch(status)
{
let data = result as! NSDictionary
case 200:
if let result = response.result.value {
completionHandler(data, nil)
}
default:
completionHandler(nil, data)
}
}
}
}