加载网址图片

时间:2017-09-21 11:30:12

标签: swift

我是IOS开发的新手,我尝试从网址加载图片,我知道swift版本之间有一些变化。 出于某种原因,我得到 imageData = nil ,我不知道为什么......

 private func fetchImage() 
 {
    let url = URL(fileURLWithPath: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png")
    if  let imageData = NSData(contentsOf: url as URL){
            image = UIImage(data: imageData as Data)
    }   
  }

2 个答案:

答案 0 :(得分:0)

您使用的错误初始值设定项为URL。那个是文件系统URL,而不是网络URL。这是您的函数的工作版本:

private func fetchImage(){
    if let url = URL(string: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png"), let imageData = try? Data(contentsOf: url){
       image = UIImage(data: imageData)
    }
}

但是,您应该完全重写您的函数,因为Data(contentsOf:)是一种同步方法,因此只应用于检索本地文件,而不是来自Internet的文件。

func fetchImage(from url:URL, completion: @escaping (UIImage?)->Void){
    URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
        guard error == nil, let data = data else {
            completion(nil);return
        }
        completion(UIImage(data: data))
    }).resume()
}

fetchImage(from: URL(string: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png")!, completion: {image in
    if let image = image {
        //use the image
    } else {
        //an error occured and the image couldn't be retrieved
    }
})

答案 1 :(得分:0)

请检查:

private func fetchImage() {
    let url = URL(string: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png")!
    let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
        if error != nil {
            print("Error Occurred: \(String(describing: error))")
        }
        else {
            if let imageData = data {
                let image = UIImage(data: imageData)
            } else {
                print("Image file is currupted")
            }
        }
    }
    task.resume()
}