自定义Operation子类:
代码实现:
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方法:
参考资料