Created
December 14, 2015 03:44
-
-
Save coreyjv/d67f4b58640f0d71a7a5 to your computer and use it in GitHub Desktop.
This shows an example of how we could use NSOperation as a return from our ApiClient which can be easily used by the UI to pass a completion block and asynchronously trigger
This file contains hidden or 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 Foundation | |
| import XCPlayground | |
| class ImageDownloader: NSOperation { | |
| let imageId: String | |
| var data: String? | |
| init(imageId: String) { | |
| self.imageId = imageId | |
| } | |
| override func main() { | |
| if self.cancelled { | |
| return | |
| } | |
| sleep(5) | |
| if self.cancelled { | |
| return | |
| } | |
| self.data = "Downloaded Image" | |
| } | |
| } | |
| class ApiClient { | |
| func getImage(imageId: String) -> ImageDownloader { | |
| return ImageDownloader(imageId: imageId) | |
| } | |
| } | |
| func exampleUiClient() { | |
| print("Start function") | |
| let queue = NSOperationQueue() | |
| let apiClient = ApiClient() | |
| let imageId = "123" | |
| let imageDownloader = apiClient.getImage(imageId) | |
| imageDownloader.completionBlock = { | |
| print("In closure.") | |
| print("Downloading of image with id \(imageId) complete") | |
| print("Image data is \(imageDownloader.data)") | |
| print("Finish closure") | |
| } | |
| queue.addOperation(imageDownloader) | |
| print("Complete function") | |
| } | |
| exampleUiClient() | |
| XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | |
| /* | |
| * Prints: | |
| * Start function | |
| * Complete function | |
| * In closure. | |
| * Downloading of image with id 123 complete | |
| * Image data is Optional("Downloaded Image") | |
| * Finish closure | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment