I use my own server, use FCM to push notifications to the ios device, push notifications are successful, I also use the Realm database system to help me store the fcm push notifications, but the storage will only succeed in the following two cases. Case1: When the app is running.
Case2: The app is killed, or running in the background, when you click to push the banner notification.
But this is not my main intention. I know that when the app is killed, I can't handle the push notifications, so I want to be able to store the push notifications when the user opens the app.
Sorry, my English is not good. If there is something unclear, please let me know.
Realm class
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 (when app runing store fcm message)
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])
}
click to push the banner notification AppDelegate.swift (when app killed or on backgroung click to push the banner notification)
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()
}
Please have experienced people to help me, thank you very much.