Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Last active September 29, 2017 12:42
Show Gist options
  • Save danielt1263/f29fe1b33941b88b0793395b68beccac to your computer and use it in GitHub Desktop.
Save danielt1263/f29fe1b33941b88b0793395b68beccac to your computer and use it in GitHub Desktop.
enum UserInteractionError: Error {
case userCanceled
}
extension UIViewController
{
func choiceIndexUsingActionSheet(title: String, message: String, choices: [String], onSourceView view: UIView) -> Promise<Int> {
return Promise(queue: DispatchQueue.main) { fulfill, reject in
let alert = UIAlertController(title: title.isEmpty ? nil : title, message: message.isEmpty ? nil : message, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in reject(UserInteractionError.userCanceled) })
let actions = choices.enumerated().map { offset, element in
UIAlertAction(title: element, style: .default, handler: { _ in fulfill(offset) })
}
for action in actions + [cancelAction] {
alert.addAction(action)
}
if let popoverPresentationController = alert.popoverPresentationController {
popoverPresentationController.sourceView = view
popoverPresentationController.sourceRect = view.bounds
}
self.present(alert, animated: true, completion: nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment