Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert url to UIImage Swift3 [duplicate]

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.

like image 771
user7778093 Avatar asked Nov 28 '22 03:11

user7778093


1 Answers

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
              }
 }
like image 173
KKRocks Avatar answered Dec 05 '22 14:12

KKRocks