Can I use UILocalNotifications and UNUserNotifications?

时间:2018-03-25 19:43:23

标签: ios cocoa-touch uilocalnotification unusernotification

I have an iOS app that includes user 'alarms' - sent to user when the the app is not in foreground. I am using UNUserNotifications and all is working well in iOS 10 and iOS 11 testing.

I would also like to reach users who are still using iOS 8 and iOS 9.

In order to send notifications to the iOS 8 users, do I need to include alternate methods that use UILocalNotifications? Or will iOS 8 respond correctly UNUserNotificatons?

If I need to include both, I can use some if's to use the right one based on OS. It just seems odd that I must include a deprecated technique.

2 个答案:

答案 0 :(得分:1)

UNUserNotifications are iOS 10 and higher, so won't work on iOS 8 and iOS 9. In that case you should check if is UNUserNotifications exists, or otherwise fall back to the older methods, eg:

if (NSClassFromString(@"UNUserNotificationCenter")) {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNAuthorizationOptions options = (UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound);

    [center requestAuthorizationWithOptions: options
                          completionHandler: ^(BOOL granted, NSError * _Nullable error) {
                              if (granted) {
                                  NSLog(@"Granted notifications!");
                              }
                          }];
}
else {
    UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: userNotificationTypes categories: nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings: settings];
}

答案 1 :(得分:0)

The UserNotifications framework was added to iOS with iOS 10, so for any version before that, you'll need to use the older UILocalNotification. You are correct that UILocalNotification was deprecated in iOS 10 in favor of UserNotifications.framework, but before iOS 10, symbols from the UserNotifications framework are unavailable, so there's no other way. You can use a simple iOS version check to determine when to use either method:

if(@available(iOS 10, *)){
    //UserNotifications method
}
else{
    //UILocalNotification method
}
相关问题