【Swift】GCD多线程和BlockOperation实用代码块

【Swift】GCD多线程和BlockOperation实用代码块_第1张图片

loadingImage.swift

//自定义一个类

import UIKit
class Downloader {
    
    class func downloadImageWithURL(_ url:String) -> UIImage! {
        let data = try? Data(contentsOf: URL(string: url)!)
        return UIImage(data: data!)
    }
}

//ViewController上的代码


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var image1: UIImageView!
    @IBOutlet weak var image2: UIImageView!
    @IBOutlet weak var image3: UIImageView!
    @IBOutlet weak var image4: UIImageView!
    
    let imageUrls = [
        "https://dn-boxueio.qbox.me/image1-big.jpg",
        "https://dn-boxueio.qbox.me/image2-big.jpg",
        "https://dn-boxueio.qbox.me/image3-big.jpg",
        "https://dn-boxueio.qbox.me/image4-big.jpg"
    ]
    
    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 clearDownload(_ sender: UIButton) {
        self.image1.image = nil
        self.image2.image = nil
        self.image3.image = nil
        self.image4.image = nil
        
        URLCache.shared.removeAllCachedResponses()
    }

     func loadImageWithURL(_ url:String) -> UIImage! {
        let data = try? Data(contentsOf: URL(string: url)!)
        return UIImage(data: data!)
        
         }

    
    @IBAction func downloadImages(_ sender: UIButton) {
        
      
        var currQueue = DispatchQueue.global(qos: .default)
      //  currQueue = DispatchQueue(label: "com.boxueio.images", attributes: .concurrent)
        //并行
        currQueue=DispatchQueue(label: "currqueue1", qos: .default, attributes: .concurrent)
        
        // dispatch_async
        currQueue.async(execute: {
            let img1 = self.loadImageWithURL(self.imageUrls[0])
            DispatchQueue.main.async(execute: {
                self.image1.image = img1
                self.image1.clipsToBounds = true
            })
        })
        
        currQueue.async(execute: {
            let img2 = self.loadImageWithURL(self.imageUrls[1])
            DispatchQueue.main.async(execute: {
                self.image2.image = img2
                self.image2.clipsToBounds = true
            })
        })
        
        currQueue.async(execute: {
            let img3 = Downloader.downloadImageWithURL(self.imageUrls[2])
            DispatchQueue.main.async(execute: {
                self.image3.image = img3
                self.image3.clipsToBounds = true
            })
        })
        
        currQueue.async(execute: {
            let img4 = Downloader.downloadImageWithURL(self.imageUrls[3])
            DispatchQueue.main.async(execute: {
                self.image4.image = img4
                self.image4.clipsToBounds = true
            })
        })
    }
}

//Operation Queue

//
//  ViewController.swift


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var image1: UIImageView!
    @IBOutlet weak var image2: UIImageView!
    @IBOutlet weak var image3: UIImageView!
    @IBOutlet weak var image4: UIImageView!
    
    let imageUrls = [
        "https://dn-boxueio.qbox.me/image1-big.jpg",
        "https://dn-boxueio.qbox.me/image2-big.jpg",
        "https://dn-boxueio.qbox.me/image3-big.jpg",
        "https://dn-boxueio.qbox.me/image4-big.jpg"
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
      //  present(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: nil)
        // 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 clearDownload(_ sender: UIButton) {
        
      //  self.image1.image=UIImage(named: <#T##String#>)
        
        self.image1.image = nil
        self.image2.image = nil
        self.image3.image = nil
        self.image4.image = nil
        
        URLCache.shared.removeAllCachedResponses()
    }

    let queue = OperationQueue()
    
    @IBAction func cancelDownload(_ sender: AnyObject) {
        self.queue.cancelAllOperations()
    }
    
    @IBAction func downloadImages(_ sender: UIButton) {
       
        
//        queue.addOperation({
//            
//            
//            let img1 = Downloader.downloadImageWithURL(self.imageUrls[0])
//            
//            OperationQueue.main.addOperation({
//                self.image1.image = img1
//                self.image1.clipsToBounds = true
//            })
//        })
//        
//        
        let op1 = BlockOperation(block: {
            let img1 = Downloader.downloadImageWithURL(self.imageUrls[0])
            
            OperationQueue.main.addOperation({
                self.image1.image = img1
                self.image1.clipsToBounds = true
            })
        })
        op1.completionBlock = { print("image1 downloaded") }
        
        let op2 = BlockOperation(block: {
            let img2 = Downloader.downloadImageWithURL(self.imageUrls[1])
            
            OperationQueue.main.addOperation({
                self.image2.image = img2
                self.image2.clipsToBounds = true
            })
        })
        op2.completionBlock = { print("image2 downloaded") }
        
        
        
        let op3 = BlockOperation(block: {
            let img3 = Downloader.downloadImageWithURL(self.imageUrls[2])
            
            OperationQueue.main.addOperation({
                self.image3.image = img3
                self.image3.clipsToBounds = true
            })
        })
        op3.completionBlock = { print("image3 downloaded") }
        
        
        
        let op4 = BlockOperation(block: {
            let img4 = Downloader.downloadImageWithURL(self.imageUrls[3])
            
            OperationQueue.main.addOperation({
                self.image4.image = img4
                self.image4.clipsToBounds = true
            })
        })
        op4.completionBlock = { print("image4 downloaded") }
        
   //     op3.addDependency(op4)
       // op2.addDependency(op3)
        
        queue.addOperation (op1)
        queue.addOperation(op4)
        queue.addOperation(op3)
        queue.addOperation(op2)
    }
}



线程并行 下载顺序

//op1先执行 op3 op 2 op4
// 1 3 2 4
op3.addDependency(op1)
op2.addDependency(op3)
op4.addDependency(op2)


queue.addOperation(op1)
queue.addOperation(op2)
queue.addOperation(op3)
queue.addOperation(op4)

你可能感兴趣的:(swift,ios,app)