Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIAlertController if iOS 8, otherwise UIAlertView

I want to conform to the UIAlertController used in iOS 8 since UIAlertView is now deprecated. Is there a way that I can use this without breaking support for iOS 7? Is there some kind of if condition I can do to check for iOS 8 otherwise do something else for iOS 7 support?

like image 219
Rocky Pulley Avatar asked Jun 17 '14 17:06

Rocky Pulley


4 Answers

I think a much better way to check if a class exists (since iOS 4.2) is:

if([ClassToBeChecked class]) {

   // use it

} else {

  // use alternative

}

In your case, that would be:

if ([UIAlertController class]) {
   // use UIAlertController

} else {
  // use UIAlertView

}
like image 141
Erwan Avatar answered Nov 10 '22 22:11

Erwan


Objective C (as mentioned above)

if ([UIAlertController class]) {
    // use UIAlertController

} else {
    // use UIAlertView

}

Swift

if objc_getClass("UIAlertController") == nil  {
       // use UIAlertView 

} else {
  // use UIAlertController

}

Don't use if NSClassFromString("UIAlertController") == nil It is not working because the signature for this method is func NSClassFromString(_ aClassName: String!) -> AnyClass!

like image 45
goce Avatar answered Nov 10 '22 21:11

goce


Please see the answer of Erwan (below my answer) as I see it is the best.

--

You can check the iOS version to use appropriate control like this:

if (([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] == NSOrderedAscending)) {
    // use UIAlertView
}
else {
    // use UIAlertController
}
like image 4
Tristian Avatar answered Nov 10 '22 21:11

Tristian


As others have already mentioned - always check whether a feature exists. I believe the safest approach is following:

if (NSClassFromString(@"UIAlertController")) {
    // use UIAlertController
} else {
    // use UIAlertView
}

With the obvious risk of entering a class name with a typo. :)

From documentation of NClassFromString:

[Returns] The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.

Availability iOS (2.0 and later)

like image 3
xius Avatar answered Nov 10 '22 20:11

xius