Reputation: 5230
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)
}
}
}
}
completionHandler(data)
stating Cannot call value of non-function type '(response: Any, error Any)'
completionHandler(nil, data)
to handle errors the best practice? PS : I am new to iOS
and Swift 3
Upvotes: 0
Views: 2028
Reputation: 2914
Use below function 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)
}
}
}
}
Upvotes: -1
Reputation: 38833
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)
Upvotes: 3