completion swift error handling code example
Example 1: swift get error from the from completion
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
print("The todo is: " + todo.description)
guard let todoTitle = todo["title"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
Example 2: swift get error from the from completion
func asynchronousWork(completion: (inner: () throws -> [String: Any]) -> Void) -> Void {
URLConnection.sendAsynchronousRequest(request, queue: queue) {
(response, data, error) -> Void in
guard let data = data else { return }
do {
guard let result = try JSONSerialization.JSONObjectWithData(data, options: [])
as? [String: Any] else {
completion(inner: { throw OurError.InvalidJSONType })
}
completion(inner: { return result })
} catch let error {
completion(inner: { throw error })
}
}
}
asynchronousWork { (inner: () throws -> [String: Any]) -> Void in
do {
let result = try inner()
} catch let error {
print(error)
}
}