0%

Trigger UIAlertAction programmatically

Sometimes you write unit testing, and have to trigger UIAlertAction without user interface.
then just do following:

Extension

1
2
3
4
5
6
7
8
9
10
11
extension UIAlertAction {
typealias AlertHandler = @convention(block) (UIAlertAction) -> Void
func trigger() {
guard let block = value(forKey: "handler") else {
XCTFail("Should not be here")
return
}
let handler = unsafeBitCast(block as AnyObject, to: AlertHandler.self)
handler(self)
}
}

Usage

1
2
3
4
let alertAction = UIAlertAction(title: "test", style: .default) { (action) in
print("action triggered!")
}
alertAction.trigger()