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

问题描述 投票:26回答:5

所以我一直在尝试向新的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

编辑:

所以把应用程序放在后台就可以了。

swift swift3 uilocalnotification ios10 unusernotificationcenter
5个回答
29
投票

你需要注册通知...我试过,这是有效的。

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是一个示例项目。


17
投票

使用Objective-C实现:

我在这里写了一个Demo项目:iOS10AdaptationTips

  1. 导入UserNotifications ///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]; } }]; 请求授权:enter image description here
  3. 安排localNotification
  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!"); } }];

然后它会显示如下:

在背景中:qazxsw poi锁屏: qazxsw poi

如果默认重复只显示一个enter image description here而不是在iOS9的锁定屏幕上显示多个:enter image description here并且还自动支持3D Touch enter image description here

我在这里写了一个演示:http://i67.tinypic.com/98t75s.jpg


1
投票

以下是几个步骤:

  1. 确保您拥有该权限。如果没有,请使用UNUserNotificationCenter.current()。requestAuthorization来获取它。或者如果您想要多次显示请求,请关注http://a67.tinypic.com/dorw3b.jpg
  2. 如果要显示通知前景,必须将UNUserNotificationCenterDelegate分配给某个地方。
  3. 告诉我代码 iOS10AdaptationTips

0
投票

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

在AppDelegate上找到此方法:

answer

找到这一行:

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

结束集:

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

如果未将演示文稿选项传递给completionHandler方法,则不会触发通知。


0
投票

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

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