Ganesh Kumar Ganesh Kumar - 1 month ago 17
Swift Question

Download Image from Url iOS 10 Swift 3

This is the function i used before to download image from url. I was using swift 2.3 version.

let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if (error == nil) {
let image: UIImage = UIImage(data: data!)!
completionBlock(succeeded: true, image: image)
}
else {
completionBlock(succeeded: false, image: UIImage(named: "user_icon")!)
}
})


Now i have converted the code to Swift 3 and the new code is given below. The below code is not calling the completion handler. Can anyone help me with this? Here is the swift 3 code.

let sessionTask = URLSession.shared
let request = URLRequest(url: url)
sessionTask.dataTask(with: request, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error == nil) {
let image: UIImage = UIImage(data: data!)!
completionBlock(true, image)
}
else {
completionBlock(false, UIImage(named: "user_icon")!)
}
})

Answer

You are not starting the task.

Store your task in a variable...

let task = session.dataTask(...

... and then start the task:

task.resume() //yes, it's always called "resume". Even if the task wasn't started yet