ios - 我可以使用 UILocalNotifications 和 UNUserNotifications 吗?

标签 ios cocoa-touch uilocalnotification unusernotification

我有一个包含用户“警报”的 iOS 应用程序 - 当应用程序不在前台时发送给用户。我正在使用 UNUserNotifications,在 iOS 10 和 iOS 11 测试中一切正常。

我还想覆盖仍在使用 iOS 8 和 iOS 9 的用户。

为了向 iOS 8 用户发送通知,我是否需要包含使用 UILocalNotifications 的替代方法?或者 iOS 8 会正确响应 UNUserNotificatons 吗?

如果我需要包括两者,我可以使用一些 if 来根据操作系统使用正确的。我必须包括一个已弃用的技术,这似乎很奇怪。

最佳答案

UNUserNotifications 适用于 iOS 10 及更高版本,因此不适用于 iOS 8 和 iOS 9。在这种情况下,您应该检查 UNUserNotifications 是否存在,否则会失败回到旧方法,例如:

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

关于ios - 我可以使用 UILocalNotifications 和 UNUserNotifications 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480178/

相关文章:

ios - 获取每周触发的 UILocalNotification

ios - 使用 Facebook iOS SDK 4.9.1 的 Swift Facebook 登录

iphone - 调用 iPhone 静态库中包含的类别的方法会导致 NSInvalidArgumentException

ios - 本地通知未触发

cocoa-touch - 如果按下主页按钮则结束比赛

iphone - RESTful iPhone 客户端和模型层次结构

Swift 每 x 天创建本地通知

ios - 使用 Dropbox 选择器在 ipad 应用程序中导入 pdf

ios - 当我们将 nil 指向 sprite 节点时会发生什么?

ios - 哪一行代码决定 iOS 项目使用 Storyboard或 Nib 或两者都不使用?