Last active
July 28, 2016 19:20
-
-
Save malcommac/a663796c162995523e6c0871e9a08820 to your computer and use it in GitHub Desktop.
How to create a simple async task in ThenAsync
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
| enum Error: ErrorType { | |
| case Network(message: String?) | |
| case EmptyData | |
| case MalformedImage(data: NSData) | |
| case DuplicateFile(path: String) | |
| case Generic(message: String) | |
| } | |
| func downloadImage(url: NSURL, in context: TaskContext) -> Task<UIImage> { | |
| let task = Task<UIImage>(in: context) { (fullfill, reject) -> (Void) in | |
| let session = NSURLSession.sharedSession() | |
| session.dataTaskWithURL(url) { (data, response, error) in | |
| if (error != nil) { // download has failed to to some network related issue | |
| reject(Error.Network(message: error!.localizedFailureReason)) | |
| return | |
| } | |
| guard let data = data else { // call returns no data | |
| reject(Error.EmptyData) | |
| return | |
| } | |
| guard let image = UIImage(data: data) else { // failed to load the image. Is it an image? | |
| reject(Error.MalformedImage(data: data)) | |
| } | |
| fullfill(image) // Okay! the image is here | |
| } | |
| } | |
| return task | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment