如何根据iOS版本处理推送通知?

时间:2014-09-20 21:30:42

标签: ios objective-c apple-push-notifications

对于iOS7,Parse使用AppDelegate中的以下代码处理推送通知:

[application registerForRemoteNotificationTypes:
 UIRemoteNotificationTypeBadge|
 UIRemoteNotificationTypeAlert|
 UIRemoteNotificationTypeSound];
然而,iOS8不支持

registerForRemoteNotificationTypes,用于处理iOS8中推送通知的新代码现在看起来像这样:

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

将这个新代码与iOS7设备一起使用会导致应用程序崩溃,因此我需要让代码确定手机所在的版本,然后运行相应的推送通知代码。我如何让应用程序检查这个,并使用正确的?

2 个答案:

答案 0 :(得分:3)

检查方法的可用性总是更好,而不是OS版本。

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)];
}

假设您的部署目标是> = 7.0。

答案 1 :(得分:0)

可能是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)];
}