提问人:Conor 提问时间:1/28/2018 最后编辑:Conor 更新时间:5/18/2018 访问量:2923
URLSession.shared.datatask 的错误处理
Error handling for URLSession.shared.datatask
问:
我有一个函数,可以查询 API,然后根据结果填充对象数组(请参阅下面的代码)。从检索到的 JSON 中,我可以使用 guard 语句来捕获任何错误,这意味着如果数据丢失,它将被捕获,但是,如果 URL 不正确或函数无法连接到 URL,则会导致应用程序在线路上崩溃
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
并给出以下错误消息
2018-01-27 23:11:28.759466+0000 myPregnancy[6321:224887] TIC Read Status [1:0x6040001729c0]: 1:57
2018-01-27 23:11:28.759940+0000 myPregnancy[6321:224887] Task <05716AF1-B1E0-4EB8-ADC7-138C026C58AC>.<1> HTTP load failed (error code: -1005 [4:-4])
2018-01-27 23:11:28.760813+0000 myPregnancy[6321:224886] Task <05716AF1-B1E0-4EB8-ADC7-138C026C58AC>.<1> finished with error - code: -1005
如何使用 guard 捕获此错误并返回类似于处理丢失数据的错误消息?
func loadMedication(){
print("Getting medication")
self.medication.removeAll()
let myUrl = URL(string: "URL HIDDEN");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "userToken=" + User.user.getUserId();
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil{
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String:Any]]
for dayData in json!{
guard let mName = dayData["name"] as? String else{
throw NSError(domain: "Name missing", code: 1, userInfo: [:])
}
guard let drugs = dayData["drugs"] as? String else{
throw NSError(domain: "Drugs missing", code: 2, userInfo: [:])
}
guard let id = dayData["id"] as? String else{
throw NSError(domain: "Id missing", code: 3, userInfo: [:])
}
guard let dateTime = dayData["dateTime"] as? String else{
throw NSError(domain: "AdministeredOn missing", code: 4, userInfo: [:])
}
guard let quantity:String = dayData["quantity"] as? String else{
throw NSError(domain: "Quantity missing", code: 5, userInfo: [:])
}
self.medication.append(
Medication(
name: mName,
drugs: drugs,
id: id,
administeredOn: dateTime,
quantity: quantity)
)
}
} catch let error as NSError{
print(error.domain)
}
self.loaded = true
print("Medication loaded")
}
task.resume()
}
答: 暂无答案
评论
Codable
Medication
if let error = error { ...
error