Skip to content

Instantly share code, notes, and snippets.

@wh1pch81n
Created March 2, 2017 04:17
Show Gist options
  • Save wh1pch81n/b9fac46cfad678d0f6a08ee3419dc60b to your computer and use it in GitHub Desktop.
Save wh1pch81n/b9fac46cfad678d0f6a08ee3419dc60b to your computer and use it in GitHub Desktop.
A helper method that will tap one of the buttons programmatically.
// Source: http://stackoverflow.com/a/40634752/3400034
extension UIAlertController {
func tapButton(at index: Int, animated: Bool) {
guard Thread.isMainThread else {
DispatchQueue.main.async {
self.tapButton(at: index, animated: animated)
}
return
}
if (0 <= index) && (index < actions.count)
, let block = actions[index].value(forKey: "handler")
{
typealias AlertHandler = @convention(block) (UIAlertAction) -> Void
let blockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(block as AnyObject).toOpaque())
let handler = unsafeBitCast(blockPtr, to: AlertHandler.self)
presentingViewController?.dismiss(animated: animated, completion: { [unowned self] in
handler(self.actions[index])
})
}
}
}
let alert = UIAlertController(title: "Hello", message: "world", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (a: UIAlertAction) in
print("tappedAction")
}))
alert.tapButton(at: 0, animated: false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment