ios - 如何在应用程序处于后台时阅读通知?

标签 ios swift push-notification

我正在使用 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/

相关文章:

ios - 使用Xcode重置证书

ios - 如何使用 Metal 将纹理缓冲区数据传递给着色器?

ios - 当我的自定义 TableView 单元格中的用户选项卡调用按钮时,如何从 json 获取号码并在拨号盘中显示该号码

ios - 迁移到 aws 后如何使用推送通知

swift - 在 TextView 中解析主题标签

ios - 在 SKSpriteNode 上设置 TVOS 中的首选焦点?

ionic-framework - 有没有办法在我们的 ionic 4 项目中使用推送通知?

IOS App保存数据到服务器

ios - 检查是否安装了谷歌地图 - iOS 10.2.1

objective-c - 将委托(delegate)作为 id 发送而不是将其设置为属性?