Skip to content

Instantly share code, notes, and snippets.

@Adobels
Last active February 6, 2020 14:24
Show Gist options
  • Save Adobels/cd6ee1455c96c8b86e959e1d3cc2803a to your computer and use it in GitHub Desktop.
Save Adobels/cd6ee1455c96c8b86e959e1d3cc2803a to your computer and use it in GitHub Desktop.
NSOperation for an async code like URLSession data tasks
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