Reputation: 160
May this question be dumb, but I was looking a way to create optional responses like Alamofire 4.0 have (eg. responseJSON,responseData, responseString etc). For example, in my project I have BaseService which make the request (using alamofire) then handle the response (for erros, if has, it calls a exception class which shows a message an break the flow). So, I have subclasses that inherit from my BaseService, and my methods has completions blocks who parse and pass any data (or error if need) from BaseService.
Theen, my question is: my BaseService request function may return (as block) a response, json or an error, ex: completionHandler(response,json, error) or completionHandler(nil, json, nil)
So when I don't need a response or json, just want verify if error isn't nil I've to do like this:
myFunc() { ( _ , _,error) in }
How do I do to get only the block that I want? Like Alamofire do with his response?
Upvotes: 0
Views: 400
Reputation: 116
You can divide your completionHandler at you BaseService
class to each service function to onSuccess
and onFail
... etc
Example:
func logInUser( _ userEmail : String, userPassword : String, onSuccess: @escaping (Any?)-> Void, onFail : @escaping (Error?) ->(Void)) {
let url : URLConvertible = urls.loginUser
let parameters = ["email" : userEmail, "password" : userPassword]
let header = ["Authorization" : APPSECRETKEY ]
alamofireManager.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header).responseJSON(completionHandler: { response in
if response.result.value != nil && response.result.error == nil {
onSuccess(response.result.value)
}
else
{
onFail(response.result.error)
}
})
}
When you call your service function:
BaseService.sharedInstance.logInUser("email", userPassword: "password",
onSuccess: { responseValue in
},
onFail: { error in
})
Upvotes: 1