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.
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)
For those wondering on how to do this in Objective-C:
//Step 1: Create a UIAlertController UIAlertController *myAlertController = [UIAlertController alertControllerWithTitle:@"MyTitle" message: @"MyMessage" preferredStyle:UIAlertControllerStyleAlert ]; //Step 2: Create a UIAlertAction that can be added to the alert UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { //Do some thing here, eg dismiss the alertwindow [myAlertController dismissViewControllerAnimated:YES completion:nil]; }]; //Step 3: Add the UIAlertAction ok that we just created to our AlertController [myAlertController addAction: ok]; //Step 4: Present the alert to the user [self presentViewController:myAlertController animated:YES completion:nil];
This will pop-up an alert that looks like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With