Completion handler paradigm in Swift 4.0.
This tutorial we are study about how to define the completion handler function and how it use. Here we are define a function in which call a webservice and handle it's response.
Completion Handler :
func getList(_ completion: @escaping (NSArray) -> ()) {
let urlPath = "url"
guard let url = URL(string: urlPath) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
let results = jsonResult["genres"] as! NSArray
print(results)
completion(results)
}
} catch {
//Catch Error here...
}
}
task.resume()
}
Handle Response :
getList { (array) in
// Lists of results.
print(array)
}
Any query about it send me message.
Thanks.
Completion handler paradigm in Swift 4.0.
Reviewed by KIRIT MODI
on
21:50:00
Rating:
No comments: