1 var topImageView = UIImageView()
2 var footImageView = UIImageView()
3 override func viewDidLoad() {
4 super.viewDidLoad()
5 // Do any additional setup after loading the view,
typically from a nib.
6 topImageView = UIImageView(frame:CGRect(x:0,
y:0, width:320, height:280))
7 self.view.addSubview(topImageView)
8
9 footImageView = UIImageView(frame:CGRect(x:0,
y:280, width:320, height:290))
10 self.view.addSubview(footImageView)
11
12 let downloadA = getOperation(name:”下载线程 A”,
imageUrl:
“http://images.apple.com/v/watch/k/images/overview/watch_03_large.jpg”,
isTopOne:true)
13
14 let downloadB = getOperation(name:”下载线程B”,
imageUrl:“http://images.apple.com/v/watch/k/images/overview/watch_05_large.jpg”,
isTopOne:false)
15
16 let queue = OperationQueue()
17 queue.maxConcurrentOperationCount = 1
18 queue.addOperation(downloadA)
19 queue.addOperation(downloadB)
20
21 for operation in queue.operations{
22 print(“Operation名称:”+operation.name!)
23 }
24 }
25 func getOperation(name:String, imageUrl:String,
isTopOne:Bool) -> BlockOperation{
26 let download = BlockOperation(block:{_ in
27 let url = URL(string:imageUrl)
28 var data:Data!
29 do{
30 Thread.sleep(forTimeInterval:1.0)
31 try data = Data(contentsOf:url!)
32 let image = UIImage(data:data)
33 if isTopOne{
34 self.perform(#selector(ViewController.showTopImage),
on:Thread.main, with: image, waitUntilDone:true)
35 }
36 else{
37
self.perform(#selector(ViewController.showFootImage), on:
Thread.main, with: image, waitUntilDone:true)
38 }
39 }catch{
40 print(“下载图片失败。”)
41 }
42 })
43 download.name = name
44 return download
45 }
46 func showTopImage(image:UIImage){
47 self.topImageView.image = image
48 }
49
50 func showFootImage(image:UIImage){
51 self.footImageView.image = image
52 }