ios 将 url 转换为 UIImage Swift3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44063314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:08:26  来源:igfitidea点击:

Convert url to UIImage Swift3

iosurlswift3uiimage

提问by user7778093

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

我尝试使用以下代码将 url 转换为 UIImage:

            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.

但这对我不起作用,不遵守 if-loop 。

回答by KKRocks

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
              }
 }

回答by Ved Rauniyar

Try this by using SDWebImage

使用SDWebImage试试这个

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