Skip to content

Instantly share code, notes, and snippets.

@Frankacy
Last active December 11, 2016 17:13
Show Gist options
  • Save Frankacy/62e46ff0d01e482bd57bb8ced919d067 to your computer and use it in GitHub Desktop.
Save Frankacy/62e46ff0d01e482bd57bb8ced919d067 to your computer and use it in GitHub Desktop.
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