在iOS 10中,UILocalNotification已被废弃。

问题描述 投票:43回答:4

这可能是一个预先提出的问题,但我想知道该用什么来代替 UILocalNotification 在iOS 10中。我正在做一个应用,它的部署目标是iOS 8,那么它是否可以在iOS 10中使用 UILocalNotification?

ios uilocalnotification
4个回答
104
投票

是的,你可以使用 "UILocalNotification"。UILocalNotification旧的API在iOS 10上也能正常工作,但我们最好使用用户通知框架中的API。还有一些新功能,你只能用iOS 10用户通知框架来使用。

远程通知也是如此,更多信息。请看这里.

新功能。

  • 现在,你可以提出警报,声音或增加徽章,而应用程序是在前台太与iOS 10。
  • 现在,当用户点击(或滑动)动作按钮时,你可以在一个地方处理所有的事件,即使是在应用程序已经被关闭的情况下。
  • 支持3D触摸而不是滑动手势。
  • 现在你可以只用一行代码就可以删除特定的本地通知。
  • 支持富通知与自定义UI。

我们真的很容易转换 UILocalNotification API到iOS 10User Notifications框架的API,它们真的很相似。

我在这里写了一个demo来演示如何同时使用新旧API。 iOS 10适配技巧 .

例如:

用Swift实现。

  1. import UserNotifications

    ///    Notification become independent from UIKit
    import UserNotifications
    
  2. 申请本地通知的授权

        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. 导入UserNotifications

    // Notifications are independent from UIKit
    #import <UserNotifications/UserNotifications.h>
    
  2. 申请本地通知的授权

    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!");
        }
    }];
    

更新的

由于未捕获异常'NSInternalInconsistencyException'而终止应用程序,原因:'如果重复,时间间隔必须至少为60'。

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

8
投票

苹果又做了一次,正确的实现是: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
投票

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

2
投票

用Objective-C实现iOS 10的本地通知。

如果你已经编程了一段时间,我相信你一定熟悉了 UILocalNotification 类,而现在随着iOS 10的到来,你可以看到,。UILocalNotification 已被废弃。详细的实施方法请访问 本博文.

© www.soinside.com 2019 - 2024. All rights reserved.