Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class LoggingOperation : Operation {
override func main() {
if isCancelled {
return;
}
print("Logging operation")
}
}
class FetchPokemonOperation : ConcurrentOperation {
var task: URLSessionDataTask?
var data: AnyObject?
override func main() {
if isCancelled {
completeOperation()
return
}
let session = URLSession(configuration: .ephemeral)
let request = URLRequest(url: URL.init(string: "http://pokeapi.co/api/v2/pokemon/151/")!)
task = session.dataTask(with: request, completionHandler: { (data, response, error) in
//Be a good citizen and remove the bangs in production, ok? :)
if self.isCancelled {
self.completeOperation()
return
}
let parsedResponse = try! JSONSerialization.jsonObject(with: data!)
self.data = parsedResponse as AnyObject
print(self.data!)
self.completeOperation()
})
task?.resume()
}
}
class ConcurrentOperation: Operation {
private var backing_executing : Bool
override var isExecuting : Bool {
get { return backing_executing }
set {
willChangeValue(forKey: "isExecuting")
backing_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
private var backing_finished : Bool
override var isFinished : Bool {
get { return backing_finished }
set {
willChangeValue(forKey: "isFinished")
backing_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
override init() {
backing_executing = false
backing_finished = false
super.init()
}
func completeOperation() {
isExecuting = false
isFinished = true
}
}
let loggingOp = LoggingOperation()
let fetchPokemonOp = FetchPokemonOperation()
let operationQueue = OperationQueue()
operationQueue.addOperation(loggingOp)
operationQueue.addOperation(fetchPokemonOp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment