UILocalNotification在iOS10中已弃用

时间:2016-06-21 08:03:43

标签: ios uilocalnotification

这可能是一个问题,但我想知道在iOS10中使用什么而不是UILocalNotification。我正在开发一个部署目标为iOS8的应用程序,所以可以使用UILocalNotification吗?

4 个答案:

答案 0 :(得分:98)

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

远程通知也会出现这种情况,有关详情:Here

新功能:

  1. 现在,您可以使用iOS 10
  2. 在应用程序处于前台时呈现警报,声音或增加徽章
  3. 现在,当用户点击(或滑动)操作按钮时,即使应用程序已被杀死,您也可以在一个地方处理所有事件。
  4. 支持3D触摸,而不是滑动手势。
  5. 现在,您只能通过一行代码删除特定的本地通知。
  6. 使用自定义UI支持Rich Notification。
  7. 我们很容易将UILocalNotification API转换为iOS10 用户通知框架API,它们非常相似。

    我在这里写了一个演示,以展示如何同时使用新旧API:iOS10AdaptationTips

    例如,

    使用Swift实现:

    1. 导入UserNotifications

      ///    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. 安排localNotification

    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"])
      }
      
    5. Objective-C实施:

      1. 导入UserNotifications

        // 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. 安排localNotification

      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!");
            }
        }];
        
      5. 转到此处获取更多信息:iOS10AdaptationTips

        更新

          

        由于未捕获的异常终止应用程序&#39; NSInternalInconsistencyException&#39;,原因:&#39;如果重复&#39;

        ,时间间隔必须至少为60
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)
        

答案 1 :(得分:8)

Apple再次做到了,正确的实现是: 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

答案 2 :(得分:2)

iOS

Objetcive-C 10的本地通知

如果您正在编程一段时间,我相信您已熟悉UILocalNotification课程,而且现在iOS 10到达时您可以看到UILocalNotification已被弃用。有关详细实施,请访问此博客文章

https://medium.com/@jamesrochabrun/local-notifications-are-a-great-way-to-send-notifications-to-the-user-without-the-necessity-of-an-b3187e7176a3#.nxdsf6h2h

答案 3 :(得分:1)

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

    }

MARK: - 代表推送通知

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