我有来自Api的大图像然后如何快速加载它。它需要花费太多时间来加载
let data = NSData(contentsOf: NSURL(string: self.imageFile)! as URL)
if data == nil{
}
else{
DispatchQueue.main.async() {
self.imageShow.image = UIImage(data: data! as Data)
}
}
这是我的代码可以任何人建议我
答案 0 :(得分:2)
您可以将此代码用于异步下载图片。
if let url = self.imageFile{
let url = URL(string: self.imageFile)
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard let data = data, error == nil else { return }
/**CHECK 404 HERE*/
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 400 {
//YOUR CODE HERE
return
}
}
DispatchQueue.main.async() { // execute on main thread
self.imageShow.image = UIImage(data: data)
}
}
task.resume()
}else{
DispatchQueue.main.async() { // execute on main thread
self.viewImageType.isHidden = true
}
}
更好的不依赖第三方图书馆
答案 1 :(得分:1)
您可以使用NSOperationQueue
在后台线程上加载图像,然后在主线程上的图像视图上加载图像。你可以通过以下方式实现这一目标:
let myQueue = OperationQueue()
myQueue.addOperation { // Load image on background thread
if let urlString = URL(string: self.imageFile) {
do {
let data = try Data(contentsOf: urlString)
DispatchQueue.main.async { // Load image on main thread
self.imageShow.image = UIImage(data: data)
}
} catch {
print("not able to load image")
}
}
}