这个问题可能很愚蠢,但我正在寻找一种方法来创建像Alamofire 4.0这样的可选响应(例如responseJSON,responseData,responseString等(。例如,在我的项目中,我有 BaseService,它发出请求(使用 alamofire(然后处理响应(对于 erros,如果有,它会调用一个异常类,该类显示一条消息中断流(。因此,我有从我的 BaseService 继承的子类,我的方法具有从 BaseService 解析和传递任何数据(或如果需要,则错误(的完成块。
Theen,我的问题是:我的 BaseService 请求函数可能会返回(作为块(响应、json 或错误,例如:completionHandler(response,json,error( 或 completionHandler(nil, json, nil(
因此,当我不需要响应或 json 时,只想验证错误是否为零,我必须这样做:
myFunc(( { ( _ , _,error( in }
我该怎么做才能只获得我想要的块?就像阿拉莫菲尔对他的回应所做的那样?
您可以将 completionHandler 划分到您BaseService
类到每个服务函数以onSuccess
和onFail
...等
例:
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)
}
})
}
调用服务函数时:
BaseService.sharedInstance.logInUser("email", userPassword: "password",
onSuccess: { responseValue in
},
onFail: { error in
})