在iOS 10中添加本地通知-Swift 3 [英] Add Local Notification in iOS 10 - Swift 3

查看:388
本文介绍了在iOS 10中添加本地通知-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在尝试向新的UNUserNotificationCenter添加通知,但我似乎没有收到.

So I been trying to add a notification to the new UNUserNotificationCenter, but I don't seem to get it.

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

My view controller has an action:

@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,但是它似乎根本没有被触发,我有什么想法吗?我正在尝试用户文档中的示例,但并没有告诉我更多信息,或者我错过了它.

And I have a Notification Content Extension in the project as well, but it does not seem to be triggered at all, any ideas what I'm missing? I'm trying the example from the user documentation, but it's not telling me much more or I have missed it.

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

也: https://developer.apple.com/reference/usernotificationsui https://developer.apple.com/reference/usernotifications

因此将应用程序置于后台就可以了.

So putting the app in the background did the trick.

推荐答案

您需要注册Notification.

You need to register for Notification...I tried and this works.

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开始显示通知.

You dont need to put your app in background to present notification from iOS 10 onwards.

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

Use below callback to configure notification to present in foreground.

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

此处是一个示例项目.

这篇关于在iOS 10中添加本地通知-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆