检查您的互联网状态并根据需要处理操作
串行调度队列
在串行队列中,每个任务在执行之前等待前一个任务完成。
当网络慢时,你可以使用它。
let serialQueue = dispatch_queue_create("com.imagesQueue", DISPATCH_QUEUE_SERIAL)
dispatch_async(serialQueue) { () -> Void in
let img1 = Downloader .downloadImageWithURL(imageURLs[0])
dispatch_async(dispatch_get_main_queue(), {
self.imageView1.image = img1
})
}
dispatch_async(serialQueue) { () -> Void in
let img2 = Downloader.downloadImageWithURL(imageURLs[1])
dispatch_async(dispatch_get_main_queue(), {
self.imageView2.image = img2
})
}
并发队列
每个下载器都被视为一个任务,所有任务都在同一时间执行。
网络快用的时候。
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) { () -> Void in
let img1 = Downloader.downloadImageWithURL(imageURLs[0])
dispatch_async(dispatch_get_main_queue(), {
self.imageView1.image = img1
})
}
dispatch_async(queue) { () -> Void in
let img2 = Downloader.downloadImageWithURL(imageURLs[1])
dispatch_async(dispatch_get_main_queue(), {
self.imageView2.image = img2
})
}
NSOPration
当你需要启动一个依赖于另一个执行的操作时,你会想要使用 NSOperation。
您还可以设置操作的优先级。
addDependency 为不同的operation
queue = OperationQueue()
let operation1 = BlockOperation(block: {
let img1 = Downloader.downloadImageWithURL(url: imageURLs[0])
OperationQueue.main.addOperation({
self.imgView1.image = img1
})
})
// completionBlock for operation
operation1.completionBlock = {
print("Operation 1 completed")
}
// Add Operation into queue
queue.addOperation(operation1)
let operation2 = BlockOperation(block: {
let img2 = Downloader.downloadImageWithURL(url: imageURLs[1])
OperationQueue.main.addOperation({
self.imgView2.image = img2
})
})
// Operation 2 are depend on operation 1. when operation 1 completed after operation 2 is execute.
operation2.addDependency(operation1)
queue.addOperation(operation2)
你也可以设置优先级
public enum NSOperationQueuePriority : Int {
case VeryLow
case Low
case Normal
case High
case VeryHigh
}
也可以设置并发操作
queue = OperationQueue()
queue.addOperation { () -> Void in
let img1 = Downloader.downloadImageWithURL(url: imageURLs[0])
OperationQueue.main.addOperation({
self.imgView1.image = img1
})
}
您也可以取消并完成操作。