IOS 多线程、进程

1 let thread = Thread.init(target:self, selector:

selector(ViewController.threadAction), object:nil)

2 thread.stackSize = 1024 * 1024

///使用线程下载图片
1 var imageView = UIImageView()
2 var label = UILabel()
接着对viewDidLoad方法进行修改,对imageView属性和label属性进
行初始化,并创建一个新的线程来执行网络图片的下载工作。
3 override func viewDidLoad() {
4 super.viewDidLoad()
5 // Do any additional setup after loading the view,
typically from a nib.
6 imageView = UIImageView(frame:CGRect(x:0, y:
260, width:320, height:300))
7 self.view.addSubview(imageView)
8
9 label = UILabel(frame:CGRect(x:0, y:0, width:
320, height:568))
10 label.backgroundColor = UIColor.white
11 label.textAlignment = .center
12 label.text = “Loading……”
13 label.font = UIFont.systemFont(ofSize:42)
14 self.view.addSubview(label)
15
16 let imageUrl =
“http://images.apple.com/v/iphone/home/s/home/images/trade_in_iphone_17 let thread = Thread(target:self, selector:

selector(ViewController.downloadImage), object: imageUrl)

18 thread.start()
19 }
20 func downloadImage(path:String){
21 let url = URL(string:path)
22 var data:Data!
23 do{
24 try data = Data(contentsOf:url!)
25 let image = UIImage(data:data)
26 self.perform(#selector(ViewController.showImage),
on:Thread.main, with:image, waitUntilDone:true)
27 }catch{
28 print(“下载图片失败。”)
29 }
30 }
31 func showImage(image:UIImage){
32 self.imageView.image = image
33 self.label.isHidden = true
34 }

你可能感兴趣的:(IOS 多线程、进程)