Swift多线程之Operation(一)

2019-10-18  本文已影响0人  只爱随便看看

自定义Operation子类:


Operation操作状态.png

代码实现:

private final class ImageDownloadOperation: Operation {
        
    let url: URL
        
    init(url: URL) {
        self.url = url
    }
    
    internal var _executing = false {
        willSet {
            willChangeValue(forKey: "isExecuting")
        }
        didSet {
            didChangeValue(forKey: "isExecting")
        }
    }
    
    override var isExecuting: Bool {
        return _executing
    }
    
    internal var _finished = false {
        willSet {
            willChangeValue(forKey: "isFinished")
        }
        didSet {
            didChangeValue(forKey: "isFinished")
        }
    }
    
    public override var isFinished: Bool {
        return _finished
    }
    
    override func start() {
        _executing = true
        
        URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
            guard let welf = self else { return }
            
            guard !welf.isCancelled else {
                welf._executing = false
                welf._finished = true
                return
            }
            
            guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
                welf._executing = false
                welf._finished = true
                return
            }
            
            guard httpResponse.statusCode == 200 else {
                welf._executing = false
                welf._finished = true
                return
            }
                        
            guard !welf.isCancelled else {
                welf._executing = false
                welf._finished = true
                return
            }
            
            //完成下载
            DispatchQueue.main.async {
                
            }
            
            //处理缓存
            
            welf._executing = false
            welf._finished = true
        }.resume()
    }
}

定义_executing,_finished的原因是因为它们只有对应的get方法:


Operation.png

参考资料

· Swift多线程之Operation:异步加载CollectionView图片

上一篇 下一篇

猜你喜欢

热点阅读