Jaseem Abbas Jaseem Abbas - 2 months ago 61
Swift Question

Swift 3 - Cannot call value of non-function type '(response: Any, error Any)'

I have written the following method in 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. I get an error at
    completionHandler(data)
    stating
    Cannot call value of non-function type '(response: Any, error Any)'

  2. Is writing
    completionHandler(nil, data)
    to handle errors the best practice?



PS : I am new to
iOS
and
Swift 3

Answer

You´re missing the return for your completionHandler -> Void and the parameter names, I added the defaults _ here:

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

}

For the error part, I would have added an onError as , onError: (NSError) -> Void) and returned onError if an error occurs. So like this:

func postFormData(url : String, parameters: Parameters!, headers : HTTPHeaders!, completionHandler : (_ response : Any,  _ error: Any) -> Void, onError: (NSError) -> Void)