當(dāng)通過(guò)url來(lái)給UIImageView設(shè)置圖片的時(shí)候需要下載圖片,如果在主線程中執(zhí)行下載圖片并設(shè)置圖片會(huì)導(dǎo)致在下載圖片的時(shí)候界面卡死。通過(guò)多線程可以解決下載任務(wù)導(dǎo)致界面卡死的問(wèn)題。
1、創(chuàng)建并使用額外的Serie Queue
letseriesQueue =DispatchQueue(label:"textGCD")
seriesQueue.async{
letimage =DownloadManager.download(url:self.imageUrls[0])
DispatchQueue.main.sync{
self.image.image= image
self.image.clipsToBounds=true
}
}
2、使用Concurrent queue并行處理
let curQueue = DispatchQueue.global()
curQueue.async {
let image = DownloadManager.download(url: self.imageUrls[0])
DispatchQueue.main.sync {
self.image1.image = image
self.image1.clipsToBounds = true
}
}
3、使用Operation Queue進(jìn)行多任務(wù)處理
let operationQueue = OperationQueue()
operationQueue.addOperation {
let image = DownloadManager.download(url: self.imageUrls[0])
OperationQueue.main.addOperation({
self.image1.image = image
self.image1.clipsToBounds = true
})
}
let operation2 = BlockOperation.init {
let image = DownloadManager.download(url: self.imageUrls[1])
OperationQueue.main.addOperation({
self.image2.image = image
self.image2.clipsToBounds = true
})
}
let operation3 = BlockOperation.init {
let image = DownloadManager.download(url: self.imageUrls[2])
OperationQueue.main.addOperation({
self.image3.image = image
self.image3.clipsToBounds = true
})
}
let operation4 = BlockOperation.init {
let image = DownloadManager.download(url: self.imageUrls[3])
OperationQueue.main.addOperation({
self.image4.image = image
self.image4.clipsToBounds = true
})
}
operation2.addDependency(operation3)
operation3.addDependency(operation4)
operation2.completionBlock = { print("task completion")}
operationQueue.addOperation(operation2)
operationQueue.addOperation(operation3)
operationQueue.addOperation(operation4)