Last active
February 6, 2020 14:24
-
-
Save Adobels/cd6ee1455c96c8b86e959e1d3cc2803a to your computer and use it in GitHub Desktop.
NSOperation for an async code like URLSession data tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OperationSource: Operation { | |
var state: Operation.OperationState = .inital | |
let newsApi: NewsApi | |
var data: Data? | |
init(newsApi: NewsApi) { | |
self.newsApi = newsApi | |
} | |
override var isFinished: Bool { | |
state == .finished | |
} | |
override var isExecuting: Bool { | |
state == .executing | |
} | |
override var isAsynchronous: Bool { true } | |
override func start() { | |
debugPrint("Test: OperationSources Start") | |
willChangeValue(forKey: #keyPath(isExecuting)) | |
state = .executing | |
didChangeValue(forKey: #keyPath(isExecuting)) | |
URLSession.shared.dataTask(with: URL(string: "https://httpbin.org/json")!) { (data, response, error) in | |
self.willChangeValue(forKey: #keyPath(isExecuting)) | |
self.willChangeValue(forKey: #keyPath(isFinished)) | |
self.state = .finished | |
self.data = data | |
self.didChangeValue(forKey: #keyPath(isFinished)) | |
self.didChangeValue(forKey: #keyPath(isExecuting)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment