Skip to content

Instantly share code, notes, and snippets.

@hurshagrawal
Created February 25, 2018 14:41
Show Gist options
  • Save hurshagrawal/9907878f4e342a738a1c9ea002660f5b to your computer and use it in GitHub Desktop.
Save hurshagrawal/9907878f4e342a738a1c9ea002660f5b to your computer and use it in GitHub Desktop.
// Copyright © 2017 Jumprope. All rights reserved.
import Foundation
// From: https://stackoverflow.com/questions/32322386/how-to-download-multiple-files-sequentially-using-nsurlsession-downloadtask-in-s
// Asynchronous operation base class
//
// This is abstract to class performs all of the necessary KVN of `isFinished` and
// `isExecuting` for a concurrent `Operation` subclass. You can subclass this and
// implement asynchronous operations. All you must do is:
//
// - override `main()` with the tasks that initiate the asynchronous task;
//
// - call `completeOperation()` function when the asynchronous task is done;
//
// - optionally, periodically check `self.cancelled` status, performing any clean-up
// necessary and then ensuring that `completeOperation()` is called; or
// override `cancel` method, calling `super.cancel()` and then cleaning-up
// and ensuring `completeOperation()` is called.
public class AsynchronousOperation: Operation {
override public var isAsynchronous: Bool { return true }
private let stateLock = NSLock()
private var _executing: Bool = false
override private(set) public var isExecuting: Bool {
get {
return stateLock.withCriticalScope { _executing }
}
set {
willChangeValue(forKey: "isExecuting")
stateLock.withCriticalScope { _executing = newValue }
didChangeValue(forKey: "isExecuting")
}
}
private var _finished: Bool = false
override private(set) public var isFinished: Bool {
get {
return stateLock.withCriticalScope { _finished }
}
set {
willChangeValue(forKey: "isFinished")
stateLock.withCriticalScope { _finished = newValue }
didChangeValue(forKey: "isFinished")
}
}
// Complete the operation
//
// This will result in the appropriate KVN of isFinished and isExecuting
public func completeOperation() {
if isExecuting {
isExecuting = false
}
if !isFinished {
isFinished = true
}
}
override public func start() {
if isCancelled {
isFinished = true
return
}
isExecuting = true
main()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment