Skip to content

marketplacer/alert-view-with-callback-swift

Repository files navigation

Show UIAlertView with callback closure in Swift

This is a helper function that allows you to show an UIAlertView and supply a callback closure to receive user input from it. It allows to use the UIAlertView without supplying a delegate object.

Deprecation notice

As you probably know UIAlertView is deprecated by Apple. Here is a replacement library for creating testable UIAlertController alerts:

https://github.com/marketplacer/TestableAlert

Setup

Copy AlertViewWithCallbackDelegate.swift and AlertViewWithCallback.swift into your project.

Usage

let alertView = UIAlertView(title: "Do you want to cancel this operation?",
  message: "", delegate: nil, cancelButtonTitle: nil,
  otherButtonTitles: "OK", "Cancel")

AlertViewWithCallback().show(alertView) { alertView, buttonIndex in
  println("You closed alert by tapping button #\(buttonIndex)")
}

Testing alert view

It is easy to verify your alert view in unit tests where you can check its title, text inputs and buttons. In addition, one can emulate user interaction by entering text into the text inputs, tapping a button and then verifying that the callback was called correctly.

In order to test your alert view simply add AlertViewWithCallbackMock.swift to your project and inject AlertViewWithCallbackMock into your app from the unit test.

See this unit test for details.

Demo

Credit

HUGE thanks to Arkku for the Objective-C example.

Project home

https://github.com/marketplacer/alert-view-with-callback-swift

About

A helper function for iOS that opens a UIAlertView and receives input in a callback closure.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages