Skip to content

Instantly share code, notes, and snippets.

@zhxnlai
Last active June 15, 2016 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhxnlai/7594df6ec62daf3d38ada9593c9b7408 to your computer and use it in GitHub Desktop.
Save zhxnlai/7594df6ec62daf3d38ada9593c9b7408 to your computer and use it in GitHub Desktop.
Async Task Extending
class ImagePickerTask : NSObject {
enum Error : ErrorType {
case PhotoLibraryNotAvailable
}
typealias CompletionHandler = [String: AnyObject]? -> ()
var completionHandler: CompletionHandler!
let viewController: UIViewController
init(viewController: UIViewController) {
self.viewController = viewController
}
}
extension ImagePickerTask : ThrowableTaskType {
typealias ReturnType = [String : AnyObject]?
func action(completion: Result<ReturnType> -> ()) {
ThrowableTask<ReturnType> {
try ThrowableTask {(callback: CompletionHandler) in
guard UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) else {
throw Error.PhotoLibraryNotAvailable
}
let controller = UIImagePickerController()
controller.sourceType = .PhotoLibrary
controller.delegate = self
self.completionHandler = callback
self.viewController.presentViewController(controller, animated: true, completion: nil)
}.await(.Main)
}.asyncResult(completion: completion)
}
}
extension ImagePickerTask : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@objc func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
completionHandler(info)
picker.dismissViewControllerAnimated(true, completion: nil)
}
@objc func imagePickerControllerDidCancel(picker: UIImagePickerController) {
completionHandler(nil)
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment