小编典典

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

swift

因此,我一直在尝试向新的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

编辑:

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


阅读 333

收藏
2020-07-07

共1个答案

小编典典

您需要注册通知。

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)

是一个示例项目。

2020-07-07