9

I have a function that queries an API and then populates an array of objects based on the results(see code below). From the JSON retrieved I can use guard statements to catch any error meaning that if data is ever missing it is captured however if the URL is incorrect or the function cannot connect to the URL it causes the app to crash on the line

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

and gives the following error message

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

How can I use guard to capture this error and return an error message similar to how I handle missing data?

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()
}
Conor
  • 736
  • 1
  • 13
  • 33
  • Your JSON-parsing looks kind of yesteryear, have you tried the `Codable` protocol for your `Medication` class/struct? Concerning your connection-errors: I would expect those to be caught by your `if let error = error { ...` line. Try printing out your `error` and tell us what kind of problem you experience with handling it. – Patru May 20 '18 at 02:37

0 Answers0