[英]How to store ios push notifications when the app is killed using swift
我使用自己的服務器,使用FCM將通知推送到ios設備,推送通知成功,我也使用Realm數據庫系統來幫助我存儲fcm推送通知,但是只有在以下兩種情況下,存儲才會成功。 情況1:應用運行時。
案例2:單擊以推送橫幅通知時,該應用程序被殺死或在后台運行。
但這不是我的主要意圖。 我知道當應用程序被殺死時,我無法處理推送通知,因此我希望能夠在用戶打開應用程序時存儲該推送通知。
對不起,我的英語不好。 如果有不清楚的地方,請告訴我。
境界類
class Order: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var name = ""
@objc dynamic var amount = ""
@objc dynamic var createDate = Date()
override static func primaryKey() -> String? {
return "id"
}
let realm = try! Realm()
let order: Order = Order()
AppDelegate.swift(當應用程序正在運行時存儲fcm消息)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo //
print("userInfo: \(userInfo)")
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: \(title) \nBody:\(body)")
order.name = title
order.amount = body
try! realm.write {
realm.add(order)
}
completionHandler([.badge, .sound, .alert])
}
單擊以推送橫幅通知AppDelegate.swift(當應用被殺死或在背景微弱時,單擊以推送橫幅通知)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print("userInfo: \(userInfo)")
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: \(title) \nBody:\(body)")
order.name = title
order.amount = body
try! realm.write {
realm.add(order)
}
completionHandler()
}
請有經驗的人來幫助我,非常感謝。
您可以在應用被終止后將通知存儲到數據庫中。
要使用“應用程序組”訪問數據庫,
var fileMgr : FileManager!
let databasePathURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>")
從上述代碼中,一旦您獲得了數據庫的路徑,就可以對數據庫執行插入操作。 這將是您正在執行的常規插入操作。
在此文件中以及下圖突出顯示的方法中插入用於保存數據的代碼。
如果您需要其他幫助,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.