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

查看:26
本文介绍了在 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/usernotificationsuihttps://developer.apple.com/reference/usernotifications

因此,将应用程序置于后台即可.

So putting the app in the background did the trick.

推荐答案

您需要注册通知...我试过了,这有效.

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天全站免登陆