我有大图像它来自 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)
}
}
这是我的代码,任何人都可以建议我
您可以使用此代码异步下载映像。
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
}
}
最好不要依赖第三方库
您可以使用
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")
}
}
}