如何从 URL 获取图像(位于要加载到 UIImageView
中的 json 字符串中)?
我已将 View 命名为 imageurl
,以使其反射(reflect)与 json 字符串相同的名称 - 我知道这不是错误。
let url = URL(string: nowplaying.data[0].track.imageurl)
let data = try? Data(contentsOf: url) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
self.imageurl.image = UIImage(data: data!)
最佳答案
使用Kingfisher
,您可以从url异步加载图像。
if var strUrl = nowplaying.data.first?.track.imageurl, strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
self.imageurl.kf.setImage(with: URL(string: strUrl), placeholder: nil)
}
它将异步从 url 加载图像,而不会阻塞主线程。
更正
if var strUrl = nowplaying.data.first?.track.imageurl {
strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.imageurl.kf.setImage(with: URL(string: strUrl), placeholder: nil)
}
关于ios - 快速加载 url 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003937/