Skip to content

Instantly share code, notes, and snippets.

@malcommac
Last active July 28, 2016 19:20
Show Gist options
  • Select an option

  • Save malcommac/a663796c162995523e6c0871e9a08820 to your computer and use it in GitHub Desktop.

Select an option

Save malcommac/a663796c162995523e6c0871e9a08820 to your computer and use it in GitHub Desktop.
How to create a simple async task in ThenAsync
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