我正在使用 swift 3 并尝试读取 didReceiveRemoteNotification
中的通知
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print(userInfo)
}
它在应用程序运行时工作,但在应用程序处于后台(非事件状态)时不打印任何内容。当应用程序处于后台(非事件状态)时,如何阅读通知。
最佳答案
在应用程序中获取后台通知的适当权限并在适当的 viewController 中采用 UNUserNotificationCenterDelegate 后。您可以实现此方法以在后台触发通知并采取操作来执行通知中的任何操作。要从通知中执行任何操作,您需要采用函数userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler finishHandler: @escaping () -> Void)
。
func startNotifications() {
let notificationCenter = UNUserNotificationCenter.current()
// to include any action in the notification otherwise ignore it.
let action = UNNotificationAction(identifier: "ActionRelatedIdentifier", title: "Name which you want to give", options: [.destructive, .authenticationRequired])
let category = UNNotificationCategory(identifier: "CategoryName", actions: [stopAction], intentIdentifiers: [], options: [])
notificationCenter.setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.title = "Your Title"
content.body = "Message you want to give"
content.sound = UNNotificationSound.default
// To trigger the notifications timely and repeating it or not
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.5, repeats: false)
content.categoryIdentifier = "CategoryName"
print("Notifications Started")
let request = UNNotificationRequest(identifier: "NotificationRequestIdentifier", content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: { (error) in
if error != nil {
print("Error in notification : \(error)")
}
})
}
免责声明:请根据您的需要应用解决方案,并询问是否发生任何错误。此代码用于触发后台通知。
关于ios - 如何在应用程序处于后台时阅读通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53259270/