有一个网络类,我为多个API类编写了多个函数。我使用Decodable来解码响应。我想将错误传递给我的ViewController,以便我可以根据错误做出正确的决定。 UserDetail
是我的模型,符合Codable。我的问题是错误完成块。如果我正在执行Nil is not compatible with expected argument type 'UserDetail'
completion(nil, error)
func getUserDetails(_ id:String, queryParamDict: [String: Any], completion:@escaping (UserDetail, Error?)-> Void)
{
let urlString = requestPathDiscovery.userDetailsURL(id, queryParamDict: queryParamDict)
sessionManager.adapter = NetworkRequestAdapter()
sessionManager.request(urlString, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { response in
guard response.result.isSuccess else {
// handle failure
return
}
if let data = response.data {
// init the decoder here
let decoder = JSONDecoder()
do{
let userResponse = try decoder.decode(UserDetail.self, from: data)
completion(userResponse, nil)
}
catch let error {
/** Here I am getting the problem **/
//completion(nil, error)
}
}
}
}
UserDetail
class UserDetail: Codable
{
var result: User
}
class User: Codable{
var d: String?
var name: String?
var phoneNumber:String?
var gender:String?
var dateOfBirth:UInt64?
}
答案 0 :(得分:0)
你的函数的completionHandler必须选择UserDetail
,因为错误情况下不会有任何用户详细信息:
func getUserDetails(_ id:String, queryParamDict: [String: Any], completion:@escaping (UserDetail?, Error?)-> Void) { ...
答案 1 :(得分:0)
更改为:
func getUserDetails(_ id:String, queryParamDict: [String: Any], completion:@escaping (UserDetail?, Error?)-> Void)
答案 2 :(得分:0)
您可以使用委托设计模式。在委托协议'onSuccess(result:yourSuccessResult)''onError(error:yourError)'上定义2方法签名。现在,如果正确获取数据,则调用委托属性'onSuccess'方法;如果发生错误,则调用'onError'。