URLSession.shared.datatask

时间:2018-01-27 23:17:14

标签: swift error-handling try-catch xcode9 do-catch

我有一个查询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()
}

0 个答案:

没有答案