Last active
December 11, 2016 17:13
-
-
Save Frankacy/62e46ff0d01e482bd57bb8ced919d067 to your computer and use it in GitHub Desktop.
A playground to go along with the article http://frankcourville.com/2016/12/05/getting-started-with-operations.html
This file contains 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
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