Check your internet status and handle a operation as require
Serial Dispatch Queues
In serial queue each task waits for the previous task to finish before being executed.
When network is slow you can use it.
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
})
}
Concurrent Queue
Each downloader is considered as a task and all tasks are being performed in same time.
When network fast use it.
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
When you need to start an operation that depends on the execution of the other, you will want to use NSOperation.
You can also set a priority of operation.
addDependency
for different 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)
You can also set a priority
public enum NSOperationQueuePriority : Int {
case VeryLow
case Low
case Normal
case High
case VeryHigh
}
You can also set a concurrent operation
queue = OperationQueue()
queue.addOperation { () -> Void in
let img1 = Downloader.downloadImageWithURL(url: imageURLs[0])
OperationQueue.main.addOperation({
self.imgView1.image = img1
})
}
you can also cancel and finish operation.