使用完成处理程序创建URLSessionTask实例时崩溃
func sessionTaskPostRequest (_ urlRequest : URLRequest , responseHandler: @escaping ResponseHandler) -> URLSessionTask {
// 5
let sesstionTask : URLSessionTask = networkSession.dataTask(with: urlRequest, completionHandler: { (data : Data? , urlResponse : URLResponse? , error : NSError? ) in
var json: NSDictionary!
do {
json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? NSDictionary
} catch {
print(error)
}
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(error != nil) {
responseHandler (false , nil , error , nil)
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
let errorJSON = parseJSON ["Err"] as! String
if !errorJSON.isEmpty {
responseHandler (false , nil , nil , errorJSON)
}else {
responseHandler (true , parseJSON , nil , nil)
}
print("Succes: \(parseJSON)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
responseHandler (false , nil , error , "Error could not parse JSON")
print("Error could not parse JSON: \(jsonStr)")
}
}
} as! (Data?, URLResponse?, Error?) -> Void)
return sesstionTask
}
为响应处理程序创建了一个类型别名,返回响应JSON对象。键入别名如下
typealias ResponseHandler = (_ successFlag :Bool , _ data : NSDictionary? , _ errorObject : NSError? , _ errorString : String?) -> Void
答案 0 :(得分:0)
似乎响应处理程序将错误对象变为NSError,如果Error对象为nil并且无法将其强制转换为NSError,它将崩溃
错误=无 并且当你因为nil对象而因NSError Typecasting失败而收到它时,如果你不做任何类型转换,同样的事情会被明智地处理