import UIKit
class ViewController: UIViewController {
let imageUrl1 = "http://img5.duitang.com/uploads/item/201312/05/20131205172110_cyw2r.thumb.700_0.jpeg"
let imageUrl2 = "http://img4.duitang.com/uploads/item/201312/05/20131205172421_QKF4K.thumb.600_0.jpeg"
@IBOutlet weak var imageView1: UIImageView!
@IBOutlet weak var imageView2: UIImageView!
@IBOutlet weak var imageView3: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startLoadingImage(sender: AnyObject) {
//self.queueLoadOneByOne()
//self.QueueWithGroup()
//self.globalQueue()
//self.tryDelayAndCancel()
//self.operationBlock()
self.operationQueue()
}
//MARK: dispatch 的大部分使用方式
//获取全局的并发线程(此处两张图片的加载时并行, 先获取先显示)
func globalQueue(){
let downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(downloadQueue, {
let image1 = self.loadImage(self.imageUrl1)
//let image2 = self.loadImage(self.imageUrl2)
dispatch_async(dispatch_get_main_queue(), {
print("load finish and show...%@...%@",NSDate(),NSThread.currentThread())
self.imageView1.image = image1
//self.imageView2.image = image2
})
})
dispatch_async(downloadQueue, {
//let image1 = self.loadImage(self.imageUrl1)
let image2 = self.loadImage(self.imageUrl2)
dispatch_async(dispatch_get_main_queue(), {
print("load finish and show...%@...%@",NSDate(),NSThread.currentThread())
//self.imageView1.image = image1
self.imageView2.image = image2
})
})
}
//使用线程group并发获取两张图片(两张图片获取成功之后再刷新视图)
func QueueWithGroup(){
let glocalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let queueGroup = dispatch_group_create()
var image1 : UIImage = UIImage()
var image2 : UIImage = UIImage()
dispatch_group_async(queueGroup, glocalQueue, {
if let image = self.loadImage(self.imageUrl1){
image1 = image
}
})
dispatch_group_async(queueGroup, glocalQueue, {
if let image = self.loadImage(self.imageUrl2){
image2 = image
}
})
dispatch_group_notify(queueGroup, glocalQueue, {
dispatch_async(dispatch_get_main_queue(), {
print("load finish and show...%@...%@",NSDate(),NSThread.currentThread())
self.imageView1.image = image1
self.imageView2.image = image2
//两张图片都下载完成之后,将其拼到一起 并延时2秒后展示
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(Double(NSEC_PER_SEC) * 2.0)), dispatch_get_main_queue(), {
print("be one...%@...%@",NSDate(),NSThread.currentThread())
let width = self.imageView1.frame.size.width
let height = self.imageView2.frame.size.height
UIGraphicsBeginImageContext(CGSizeMake(width * 2, height))
image1.drawInRect(CGRectMake(0, 0, width, height))
image2.drawInRect(CGRectMake(width, 0, width, height))
let imageInOne = UIGraphicsGetImageFromCurrentImageContext()
self.imageView3.image = imageInOne
UIGraphicsEndImageContext()
})
})
})
}
//使用新建串型线程 同步获取
func queueLoadOneByOne(){
let serialQueue = dispatch_queue_create("huangyuanqing", nil)
dispatch_async(serialQueue, {
let image = self.loadImage(self.imageUrl1)
dispatch_async(dispatch_get_main_queue(), {
print("load finish and show...%@...%@",NSDate(),NSThread.currentThread())
self.imageView1.image = image
})
})
dispatch_async(serialQueue, {
let image = self.loadImage(self.imageUrl2)
dispatch_async(dispatch_get_main_queue(), {
print("load finish and show...%@...%@",NSDate(),NSThread.currentThread())
self.imageView2.image = image
})
})
}
func loadImage(url : String) -> UIImage?{
print("start download picture...%@...%@",NSDate(),NSThread.currentThread())
let requestUrl = NSURL.init(string: url)
let imageData = NSData.init(contentsOfURL: requestUrl!)
if let data = imageData{
return UIImage.init(data: data)
}
return nil
}
func tryDelayAndCancel(){
print("2 seconds later i will call 110 now is",NSDate())
let task = delay(2.0, task: {
print("call 110",NSDate())
})
self.cancel(task)
}
typealias Task = (cancel : Bool) -> ()
func delay(time:NSTimeInterval, task:()->()) -> Task? {
func dispatch_later(block:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(time * Double(NSEC_PER_SEC))),
dispatch_get_main_queue(),
block)
}
var closure: dispatch_block_t? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if let internalClosure = closure {
if (cancel == false) {
dispatch_async(dispatch_get_main_queue(), internalClosure);
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if let delayedClosure = result {
delayedClosure(cancel: false)
}
}
return result;
}
func cancel(task:Task?) {
print("it's not a good idea cancel it at",NSDate())
task?(cancel: true)
}
//MARK: NSThread
//MARK: NSOperation
func operationBlock(){
let oBlock = NSBlockOperation()
var image1 : UIImage? = UIImage()
var image2 : UIImage? = UIImage()
oBlock.addExecutionBlock({
print("start download picture...%@...%@",NSDate(),NSThread.currentThread())
image1 = self.loadImage(self.imageUrl1)
})
oBlock.addExecutionBlock({
print("start download picture...%@...%@",NSDate(),NSThread.currentThread())
image2 = self.loadImage(self.imageUrl2)
})
oBlock.completionBlock = {
print("finished and show...%@...%@",NSDate(),NSThread.currentThread())
self.imageView1.image = image1
self.imageView2.image = image2
}
oBlock.start()
}
//使用operationqueue并发多线程下载图片 下载完成使用nsthread mainthread刷新ui
func operationQueue(){
let operationQueue = NSOperationQueue()
var image1 : UIImage? = UIImage()
var image2 : UIImage? = UIImage()
let block1 = NSBlockOperation()
let block2 = NSBlockOperation()
block1.addExecutionBlock({
print("start download picture one...%@...%@",NSDate(),NSThread.currentThread())
image1 = self.loadImage(self.imageUrl1)
})
block2.addExecutionBlock({
print("start download picture two...%@...%@",NSDate(),NSThread.currentThread())
image2 = self.loadImage(self.imageUrl2)
})
block1.completionBlock = {
self.performSelectorOnMainThread(Selector("refreshUI1:"), withObject: image1, waitUntilDone: false)
}
block2.completionBlock = {
self.performSelectorOnMainThread(Selector("refreshUI2:"), withObject: image2, waitUntilDone: false)
}
operationQueue.addOperation(block1)
operationQueue.addOperation(block2)
}
func refreshUI1(image : UIImage){
print("finished and show picture one...%@...%@",NSDate(),NSThread.currentThread())
self.imageView1.image = image
}
func refreshUI2(image : UIImage){
print("finished and show picture two...%@...%@",NSDate(),NSThread.currentThread())
self.imageView2.image = image
}
}
文中封装delay函数转自 http://swifter.tips/gcd-delay-call/ 作者:王巍 (@ONEVCAT)