【问题标题】:Can I use UILocalNotifications and UNUserNotifications?我可以使用 UILocalNotifications 和 UNUserNotifications 吗?
【发布时间】:2018-09-03 22:21:56
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: ios cocoa-touch uilocalnotification unusernotification


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      The UserNotifications framework 已通过 iOS 10 添加到 iOS,因此对于之前的任何版本,您都需要使用较旧的 UILocalNotification。你是对的,UILocalNotification 在 iOS 10 中被弃用,取而代之的是 UserNotifications.framework,但在 iOS 10 之前,来自 UserNotifications 框架的符号不可用,所以没有其他办法。您可以使用简单的 iOS 版本检查来确定何时使用任一方法:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-02
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        相关资源
        最近更新 更多