Swift 3 - 不能调用非函数类型的值'(响应:任何,错误Any)'

时间:2016-10-06 19:21:44

标签: ios swift alamofire

我在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)
                }
            }
    }

}
  1. 我在completionHandler(data)陈述Cannot call value of non-function type '(response: Any, error Any)'
  2. 时收到错误消息
  3. completionHandler(nil, data)来处理错误是最佳做法吗?
  4. PS:我是iOSSwift 3

    的新手

2 个答案:

答案 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)
            }
        }
    }
}