iOS 10 中弃用了 UILocalNotification

UILocalNotification is deprecated in iOS 10

这可能是一个提前的问题,但我想知道在 iOS 10 中使用什么代替 UILocalNotification。我正在开发一个具有部署目标 iOS 8 的应用程序,所以使用 UILocalNotification 可以吗?

是的,您可以使用 UILocalNotification,旧的 API 也适用于 iOS 10,但我们最好改用用户通知框架中的 API。还有一些新功能,您只能使用 iOS 10 User Notifications 框架。

这也发生在远程通知中,有关更多信息:

新功能:

  • 现在您也可以使用 iOS 10
  • 在应用程序处于前台时显示警报、声音或增加徽章
  • 现在您可以在用户点击(或滑动)操作按钮时在一处处理所有事件,即使应用已被终止。
  • 支持 3D 触摸而不是滑动手势。
  • 现在只需一行代码即可删除特定的本地通知。
  • 支持自定义丰富的通知 UI。

我们很容易将UILocalNotification API 转换为iOS 10 User Notifications framework API,它们真的很相似。

我在这里写了一个演示来展示如何同时使用新旧API:iOS 10 Adaptation Tips .

例如,

使用 Swift 实现:

  1. 导入用户通知

    ///    Notification become independent from UIKit
    import UserNotifications
    
  2. 请求 localNotification 授权

        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    
  3. 安排本地通知

  4. 更新应用程序图标徽章编号

    @IBAction  func triggerNotification(){
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil)
        content.sound = UNNotificationSound.default()
        content.badge = UIApplication.shared().applicationIconBadgeNumber + 1;
        content.categoryIdentifier = "com.elonchan.localNotification"
        // Deliver the notification in 60 seconds.
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        // Schedule the notification.
        let center = UNUserNotificationCenter.current()
        center.add(request)
    }
    
    @IBAction func stopNotification(_ sender: AnyObject) {
        let center = UNUserNotificationCenter.current()
        center.removeAllPendingNotificationRequests()
        // or you can remove specifical notification:
        // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"])
    }
    

Objective-C 实施:

  1. 导入用户通知

    // Notifications are independent from UIKit
    #import <UserNotifications/UserNotifications.h>
    
  2. 请求 localNotification 授权

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];
    
  3. 安排本地通知

  4. 更新应用程序图标徽章编号

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:"
                                                        arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!"
                                                       arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    content.badge = [NSNumber numberWithInteger:([UIApplication sharedApplication].applicationIconBadgeNumber + 1)];
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                triggerWithTimeInterval:5.f
                                                repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                        content:content
                                                                        trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@"add NotificationRequest succeeded!");
        }
    }];
    

已更新

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)

苹果又做了一次,正确的实现是: AppDelegate.swift

if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.currentNotificationCenter()
        center.requestAuthorizationWithOptions([.Alert, .Sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    } else {
        // Fallback on earlier versions
    }

别忘了添加

import UserNotifications

iOS 10 在 Objective-C 的本地通知。

如果您已经编程了一段时间,我相信您对 UILocalNotification class 很熟悉,现在随着 iOS 10 的到来,您可以看到 UILocalNotification 已弃用。如需详细实施,请访问 this blog post.

swift 4

if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .badge, .sound])  { (granted, error) in
            // Enable or disable features based on authorization.
        }
    } else {
        // REGISTER FOR PUSH NOTIFICATIONS
        let notifTypes:UIUserNotificationType  = [.alert, .badge, .sound]
        let settings = UIUserNotificationSettings(types: notifTypes, categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
        application.applicationIconBadgeNumber = 0

    }

马克:- 推送通知代表

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let installation = PFInstallation.current()
    installation?.setDeviceTokenFrom(deviceToken)
    installation?.saveInBackground(block: { (succ, error) in
        if error == nil {
            print("DEVICE TOKEN REGISTERED!")
        } else {
            print("\(error!.localizedDescription)")
        }
    })
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print("\(userInfo)")

    // PFPush.handle(userInfo)
    if application.applicationState == .inactive {
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(inBackground: userInfo, block: nil)
    }
}