![](/img/trans.png)
[英]Http request from iOS push notification action when app is in background
[英]IOS trigger notification action when app is in the background
從遠程通知打開應用程序時,我的應用程序執行以下操作。 基本上,它將article_id
保存在UserDefaults
以便我可以在應用程序啟動時使用它:
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()
}
}
但是,這僅在應用程序完全關閉時才有效。 如果應用程序保持在后台並且用戶單擊通知(例如從鎖定屏幕),則不會觸發上述功能。 因此,它不會將數據保存到我的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 中的以下代碼在啟動時獲取通知內容:
let notificationOption = launchOptions?[.remoteNotification]
if let notification = notificationOption as? [String: AnyObject] {
}
最后,確保您在項目設置中啟用了“遠程通知”后台模式:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.