在 iOS 10 - Swift 3 中添加本地通知

Add Local Notification in iOS 10 - Swift 3

所以我一直在尝试向新的 UNUserNotificationCenter 添加通知,但我似乎没有收到。

我的视图控制器有一个动作:

@IBAction func sendPressed(_ sender: AnyObject) {
    let content = UNMutableNotificationContent()

    content.title = "Hello"
    content.body = "What up?"
    content.sound = UNNotificationSound.default()

    // Deliver the notification in five seconds.
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)

    // Schedule the notification.
    let center = UNUserNotificationCenter.current()
    center.add(request) { (error) in
        print(error)
    }
    print("should have been added")
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization([.alert, .sound]) { (granted, error) in
    }
}

而且我在项目中也有一个 Notification Content Extension,但它似乎根本没有被触发,我缺少什么想法?我正在尝试用户文档中的示例,但它并没有告诉我更多信息,或者我已经错过了。

此处:https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent

还有: https://developer.apple.com/reference/usernotificationsui https://developer.apple.com/reference/usernotifications

编辑:

所以将应用程序置于后台就可以了。

您需要注册通知...我试过了并且有效。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
        return true
    }

编辑: 从 iOS 10 开始,您无需将应用置于后台即可显示通知。

使用下面的回调将通知配置为在前台显示。

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

Here 是示例项目。

使用 Objective-C 实现:

我在这里写了一个Demo工程:iOS10AdaptationTips .

  1. 导入用户通知

    ///Notification become independent from Foundation
    @import UserNotifications;
    
  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. 更新应用程序图标徽章编号

        //        //Deliver the notification at 08:30 everyday
        //        NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
        //        dateComponents.hour = 8;
        //        dateComponents.minute = 30;
        //        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
    
        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 = @([[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!");
            }
        }];
    

那么会出现这样的:

在后台: 锁定屏幕:

如果Repeat默认只显示一个 而不是在 iOS9 的锁定屏幕上显示很多: 并且自动支持3D Touch

我在这里写一个Demo:iOS10AdaptationTips .

我按如下方式解决了我的问题(Firebase,Swift 3):

Find this method on your AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

Find this line:

completionHandler()

End set:

completionHandler([.alert,.sound,.badge])

如果您没有将演示选项传递给 completionHandler 方法,则不会触发通知。

我已经为 Swift 3 做了一个实现,这可能有帮助,你可以在这里查看:

这里有几个步骤:

  1. 确保您拥有权限。如果没有,请使用 UNUserNotificationCenter.current().requestAuthorization 来获取它。或者如果你想显示请求弹出不止一次,请按照

  2. 如果你想显示通知 foreground,必须将 UNUserNotificationCenterDelegate 分配给某个地方。

  3. 给我看代码

    @IBAction func sendPressed(_ sender: AnyObject) {
        let content = UNMutableNotificationContent()
        content.title = "Hello"
        content.body = "What up?"
        content.sound = UNNotificationSound.default()
    
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error) in
            print(error)
        }
    }
    
    override func viewDidLoad(_ animated: Bool) {
        super.viewDidLoad(animated)
    
        // Assign the delegate
        UNUserNotificationCenter.current().delegate = self
    
        // Ask the permission
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
            if granted {
                // do something
            }
        }
    }
    // Remember to add UNUserNotificationCenterDelegate to your view controller
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Got the msg...")
        completionHandler([.badge, .sound, .alert])
    }