将url转换为UIImage Swift3

时间:2017-05-19 06:52:13

标签: ios url swift3 uiimage

我尝试使用以下代码将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()

但它对我不起作用,if-loop未被编译。

2 个答案:

答案 0 :(得分:26)

试试这个

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

使用后台主题

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

答案 1 :(得分:0)

使用SDWebImage

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