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.
becomes
Swift 2.0:
Use AlertController.
Example for Action Sheet:
Example for Alerts:
1)
2) Alert With TextField in it.
3)
For those wondering on how to do this in Objective-C:
This will pop-up an alert that looks like this:
The examples above didn't help me much. My solution is for XCode 6.4., Swift 1.2 and you can copy and paste this code in a test project to get a feeling how it works :
SOLUTION 1 - Swift 1.2 :
I checked this solution in Xcode 7.0. It worked. Xcode made one change. I recompiled it in Xcode 6.4 again and it worked. The changes for Swift 2.0 should be minor if existent at all.
Hope this helps ;)
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):
So the compact code will look like:
Where
self
here is supposed to be yourUIViewController
.Additional tip: if you need to call that code that displays the alert outside of the context of an
UIViewController
, (whereself
is not anUIViewController
) you can always use the root VC of your app:(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)I think this is the way to have backward compatibility for older iOS SDK and to use new API when using newer SDK. Also it is without warnings for deprecation in code using deprecated class.