6

I try to convert url to UIImage by using following code :

            let url = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
            let sessionTask = URLSession.shared
            let request = URLRequest(url: url!)
            let task = sessionTask.dataTask(with: request, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in
                if (error == nil) {
                    let image: UIImage = UIImage(data: data!)!

                }

            })
            task.resume()

but it's not work for me, if-loop is not complied.

3
  • Check what is the value of error object Commented May 19, 2017 at 6:54
  • stackoverflow.com/a/39813761/2526932 Commented May 19, 2017 at 6:55
  • This code is working in xcode 8.3 Commented May 19, 2017 at 7:13

2 Answers 2

40

Try this

    let url = URL(string:"http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
    if let data = try? Data(contentsOf: url!)
    {
      let image: UIImage = UIImage(data: data)
    }

With Background thread

 DispatchQueue.global(qos: .background).async {
        do
         {
              let data = try Data.init(contentsOf: URL.init(string:"url")!)
               DispatchQueue.main.async {
                  let image: UIImage = UIImage(data: data)
               }
         }
        catch {
               // error
              }
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much. you can save my time. ><
Welcome.....@user7778093
What would be the benefit of doing teh conversion in a background thread?
@QTheGreat It will improve the performance of the application. Ex. Lagging of application during downloading the image.
@KKRocks small changes in this code . Please add the optional for image let image: UIImage? = UIImage(data: data). This is for Swift 5
|
1

Try this by using SDWebImage

imageView.sd_setImage(with: URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png"), placeholderImage: UIImage(named: "placeholder.png"))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.