我试图将请求响应(以JSON的形式)序列化为模型 - JSON可能有时会遗漏某些属性,因此我尝试使用方法here来保护反对。
但是,模型从模型中抛出经典的fatal error: unexpectedly found nil while unwrapping an Optional value
- 模型试图强制从responseObject JSON中打开init调用的非可选值 - 但是因为它没有存在,力量展开失败。
从Alamofire处理此问题的最佳解决方案是什么?
型号:
final public class User: ResponseObjectSerializable {
let username: String
let name: String
public init?(response: NSHTTPURLResponse, representation: AnyObject) {
self.username = representation.valueForKeyPath("username") as! String
self.name = representation.valueForKeyPath("name") as! String
}
}
Alamofire请求延期:
import Foundation
import Alamofire
public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let
response = response,
responseObject = T(response: response, representation: value)
{
return .Success(responseObject)
} else {
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
客户请求:
Alamofire.request(.GET, requestUrl, parameters: params, encoding: .URL)
.validate()
.responseObject { (response: Response<User, NSError>) in
switch response.result {
case .Success(let user):
completionHandler(user, nil)
case .Failure(let error):
print("Request failed with error: \(error)")
completionHandler(nil, error)
}
}
return self
答案 0 :(得分:1)
您的User
课程中有一个可用的初始化程序,但您似乎没有使用它。
这是我想到的简单版本:
class User {
let firstName: String
init?(name: String?) {
guard let name = name else {
self.firstName = "" // trash value needed until swift 2.2
return nil
}
self.firstName = name
}
}