How to create dispatch queue in Swift 3

前端 未结 15 2096
余生分开走
余生分开走 2020-11-22 16:35

In Swift 2, I was able to create queue with the following code:

let concurrentQueue = dispatch_queue_create(\"com.swift3.imageQueue\", DISPATCH_QUEUE_CONCURR         


        
15条回答
  •  萌比男神i
    2020-11-22 17:34

    Compiles under >=Swift 3. This example contains most of the syntax that we need.

    QoS - new quality of service syntax

    weak self - to disrupt retain cycles

    if self is not available, do nothing

    async global utility queue - for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.

    async main queue - for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.

    Of course, you need to add some error checking to this...

    DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in
    
        guard let strongSelf = self else { return }
    
        strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in
    
            if error != nil {
                print("error:\(error)")
            } else {
                DispatchQueue.main.async { () -> Void in
                    activityIndicator.removeFromSuperview()
                    strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
                }
            }
        }
    }
    

提交回复
热议问题