简体   繁体   中英

How to handle push notifications depending on iOS version?

For iOS7, Parse handled push notifications with the following code in AppDelegate:

[application registerForRemoteNotificationTypes:
 UIRemoteNotificationTypeBadge|
 UIRemoteNotificationTypeAlert|
 UIRemoteNotificationTypeSound];

registerForRemoteNotificationTypes isn't supported in iOS8 however, and the new code used to handle push notifications in iOS8 now looks like this:

UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert |
 UIUserNotificationTypeBadge |
 UIUserNotificationTypeSound
                                  categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];

Using this new code with an iOS7 device causes the app to crash, so I need to have the code determine which version the phone is on, and run the appropriate push notification code. How can I have the app check this, and use the correct one?

It's always better to check the availability of methods, rather than OS version.

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)]) {

    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];

    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

    [[UIApplication sharedApplication] registerForRemoteNotifications];

} else {

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}

Assuming your deployment target is >= 7.0.

Possibly a duplicate of registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM