How do I migrate from UIAlertView (deprecated in iOS8)

Dom Bryan picture Dom Bryan · Jun 19, 2015 · Viewed 37.4k times · Source

I currently have the following line of code in one of my apps. It is a simple UIAlertView. However, as of iOS 8, this is now deprecated:

let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")

How do I update this to work with iOS 8+? I believe I have to change something to UIAlertCotroller, though I'm not too sure what.

Answer

AliSoftware picture AliSoftware · Jun 19, 2015

You need to use UIAlertController instead. To class documentation is pretty straightforward, even containing an usage example in Listing 1 at the very beginning of the doc (sure it's in ObjC and not in Swift but it's quite similar).

So for your use case, here is how it translates to (with added comments):

let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { _ in
  // Put here any code that you would like to execute when
  // the user taps that OK button (may be empty in your case if that's just
  // an informative alert)
}
alert.addAction(action)
self.presentViewController(alert, animated: true){}

So the compact code will look like:

let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.present(alert, animated: true){}

Where self here is supposed to be your UIViewController.


Additional tip: if you need to call that code that displays the alert outside of the context of an UIViewController, (where self is not an UIViewController) you can always use the root VC of your app:

let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
rootVC?.presentViewController(alert, animated: true){}

(But in general it's preferable to use a known UIViewController when you have one — and you generally present alerts from UIViewControllers anyway — or try to get the most suitable one depending on your context instead of relying on this tip)