天天看点

Swift 系统学习 34 线程通信 Swift3.0 子线程下载图片主线程显示图片

import UIKit

class ViewController: UIViewController {
    
    var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        self.view.addSubview(imageView)
        // Do any additional setup after loading the view, typically from a nib.
        
        // 程序启动后开子线程下载图片,图片下载完成之后回到主线程设置图片
        Thread.detachNewThreadSelector(#selector(ViewController.downloadImage), toTarget: self, with: nil)
        
    }
    
    func downloadImage() {
        // 获得要下载图片的url
        let url = NSURL.init(string: "http://cdn.cocimg.com/assets/images/logo.png")
        // 把url地址指向资源的二进制下载到本地
        let imageData = NSData.init(contentsOf: url! as URL)
        // 把二进制数据转换为图片
        let image = UIImage.init(data: imageData! as Data)
        
        // 打印查看当前线程(应该是在子线程中下载图片)
        print("当前线程为\(Thread.current)")
        
        // 线程间通信
        self.performSelector(onMainThread: #selector(ViewController.showImage), with: image, waitUntilDone:true)
        
    }
    
    func showImage(image:UIImage) {
        imageView.image = image
        print("处理UI刷新操作的线程:\(Thread.current)")
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}