首页 > 解决方案 > 将所有从“Firebase 推送通知”接收的消息存储在移动数据库/本地

问题描述

我正在尝试使用UserDefaults将来自 firebase 推送通知的所有消息存储在移动数据库中。但它只存储最新消息。但我希望数据库存储所有接收消息。请帮我解决这个问题。我被这个困住了。

 let notificationBody = userInfo[AnyHashable("text")]! as! String
 UserDefaults.standard.set(notificationBody, forKey: "notifications") 

---- 这仅打印最后一个通知-----

标签: iosswiftfirebasepush-notificationuserdefaults

解决方案


每次使用此代码存储通知时,它都会覆盖当前值。这就是为什么您只收到最新消息的原因。您可以创建一个通知数组并将其存储在 userDefaults 中。然后每次收到新通知时,您都可以将新通知附加到 UserDefaults 中的当前通知数组

首先你为通知创建一个可编码的类

class FNotifications: Codable {
  let fnotifications:[FNotification]

    init(fnotifications:[FNotification]) {
        self.fnotifications = fnotifications
    }
}

class FNotification: Codable {

    let id:String
    let type:Int
    let header:String
    let description:String
    let date:String
    let badge:Int
    var status: UInt8

    init(id:String,type:Int,header:String,description:String,date:String,badge:Int,status:UInt8, recordID:String) {
        self.id = id
        self.type = type
        self.header = header
        self.description = description
        self.date = date
        self.badge = badge
        self.status = status
    }
}

然后您可以创建一个 FNotification 数组并将其存储到 userDefaults (仅在您第一次想要创建数组时。第二次您可以获得保存的数组并将新通知附加到它)

//define notification array when its first time
var notification: [FNotification] = []

//add new notification to array
notification.append(FNotification(id: "" ,type: "",header: "", description: "", date:"" , badge: 1, status: 1))

do{
//save to user defaults
UserDefaults.standard.set(try? PropertyListEncoder().encode(notification), forKey: "notifications")
UserDefaults.standard.synchronize()

}catch{
    print(error)
}

使用这种方式保存通知后,您可以获得这样的通知

if let notiArray =  UserDefaults.standard.object(forKey: "notifications") as? Data {
        if notiArray.count != 0 {
            notification = try! PropertyListDecoder().decode(Array<FNotification>.self, from: notiArray)
            print("notification \(notification)")
        }
 }

推荐阅读