当应用程序位于后台时,IOS触发通知操作
从远程通知打开应用程序时,我的应用程序会执行以下操作。基本上,它在当应用程序位于后台时,IOS触发通知操作,ios,notifications,Ios,Notifications,从远程通知打开应用程序时,我的应用程序会执行以下操作。基本上,它在UserDefaults中保存article\u id,以便在应用程序启动时使用: extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotifica
UserDefaults
中保存article\u id
,以便在应用程序启动时使用:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
if let aps = userInfo["aps"] as? [String: AnyObject] {
let article_id = aps["article_id"]
UserDefaults.standard.set(article_id, forKey: "notification_article_id")
}
completionHandler()
}
}
然而,这只有在应用程序完全关闭时才有效。如果应用程序仍在后台,并且用户单击通知(例如从锁定屏幕),则不会触发上述功能。因此,它不会将数据保存到my
UserDefaults
中。有人知道在这种情况下如何触发类似的行动吗?提前谢谢 您的扩展委托函数声明是正确的,应该在您描述的状态下启动(锁定屏幕、主屏幕、应用程序背景)。请确保已将代理设置为:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
}
如果已经设置了,我将验证您的解析代码是否正确,并在模拟器或其他设备上进行测试。我经常使用xcrun simctl在模拟器中测试推送通知。您可以通过创建一个名为“payload.json”的虚拟测试文件,并在终端中执行以下命令来实现这一点:
xcrun simctl push booted com.yourapp.bundle.id payload.json
这是payload.json的一个示例:
{
"Simulator Target Bundle": "com.yourapp.bundle.id",
"aps":{
"alert":{
"title":"Egon Spengler",
"body":"I collect spores, molds, and fungus"
},
"sound":"alert.caf",
"badge":3
},
"alert":{
"alertUuid":"asdfasdfasdfasdfasdf",
"state":1,
"lastUpdate":"2020-11-8T21:43:57+0000"
}
}
如果应用程序已终止,您可以在didFinishLaunchingWithOptions中使用以下代码在启动时获取通知内容:
最后,确保已在项目设置中启用“远程通知”后台模式:
谢谢,我已经设置了
unuservicentificationcenter.current().delegate=self
,如果应用程序是从通知打开的(不是从后台激活的),我的代码可以工作。问题是,如果应用程序已经在手机的后台,则不会调用该功能。因为该应用程序未“启动”,但已重新激活。@OUO该应用程序是后台启动还是终止?我添加了代码来处理应用程序终止时的通知。请试一试。我问的是背景应用程序。因此,应用程序没有终止。那是在后台。例如,当用户在未终止应用程序的情况下锁定屏幕,或当我的应用程序仍在后台时打开另一个应用程序时。@OUO在项目配置中目标的“签名和功能”选项卡下,您将看到一个名为“后台模式”的部分。选中“后台提取”和“远程通知”。我假设您已经将推送通知添加到您的功能中。
let notificationOption = launchOptions?[.remoteNotification]
if let notification = notificationOption as? [String: AnyObject] {
}