Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ask for Permission for Local Notifications in iOS 8, but still have the App Support iOS 7

I have an app which uses local notifications. In iOS 7 everything works fine, but in iOS 8 the app needs to ask for user permission to display notifications. To ask for permission in iOS 8 I'm using:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  {   [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; } 

It works fine in Xcode 6 and in iOS 8. When I open the same project in Xcode 5, the error is a Semantic Issue. "Use of undeclared identifier 'UIUserNotificationSettings'."

How can I get the app to work with iOS 7 & 8, and have the notifications work properly on both versions.

like image 735
dannysandler Avatar asked Jul 25 '14 01:07

dannysandler


People also ask

When should you ask for notification permission?

Generally speaking, you should ask users for permissions only when absolutely necessary and only after ensuring that users understand how granting this access will benefit them.


1 Answers

The following answer makes a few assumptions:

  1. The app must build properly with a Base SDK of iOS 8 when using Xcode 6 and it must build properly with a Base SDK of iOS 7 when using Xcode 5.
  2. The app must support a Deployment Target of iOS 7 (or earlier) regardless of the Base SDK and Xcode version.

Code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {     // None of the code should even be compiled unless the Base SDK is iOS 8.0 or later #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000     // The following line must only run under iOS 8. This runtime check prevents     // it from running if it doesn't exist (such as running under iOS 7 or earlier).     if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {         [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];     } #endif } 

All of this is covered in the Apple SDK Compatibility Guide.

like image 174
rmaddy Avatar answered Oct 06 '22 16:10

rmaddy