Skip to content

Instantly share code, notes, and snippets.

@cipolleschi
Last active June 14, 2020 14:50
Show Gist options
  • Select an option

  • Save cipolleschi/5e23c4e2f5bdf6124f7302c6a023a5ac to your computer and use it in GitHub Desktop.

Select an option

Save cipolleschi/5e23c4e2f5bdf6124f7302c6a023a5ac to your computer and use it in GitHub Desktop.
// Data structure to hold the title of the UIAlertAction and the value that will resolve the promise
struct AlertCommand<T> {
let title: String
let returnValue: T
}
// Promisified implementation of the userTapDialog function
func userTapDialog() {
_ = presentAlertVC(
title: "Question!",
message: "What's your favourite color?",
commands: [
AlertCommand(title: "Red", returnValue: "Red"),
AlertCommand(title: "Blue", returnValue: "Blue"),
]).then(in: .main) { dialogResult in
self.localState.color = dialogResult
}
}
// Helper that allows to transform an alert control with callbacks into a promise
func presentAlertVC<T>(title: String, message: String, commands: [AlertCommand<T>]) -> Promise<T> {
// Create the promise in the main thread because we need to present it.
// Being UI code, it has to run in the main thread.
return Promise<T>(in: .main) { resolve, _, _ in
let alertControl = UIAlertController(
title: title,
message: message,
preferredStyle: .alert
)
// add commands
commands.forEach { command in
alertControl.addAction(UIAlertAction(title: command.title, style: .default, handler: { _ in
resolve(command.returnValue)
}))
}
// present alert
self.present(alertControl, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment