ios - 将所有从“Firebase 推送通知”接收的消息存储在移动数据库/本地
问题描述
我正在尝试使用UserDefaults将来自 firebase 推送通知的所有消息存储在移动数据库中。但它只存储最新消息。但我希望数据库存储所有接收消息。请帮我解决这个问题。我被这个困住了。
let notificationBody = userInfo[AnyHashable("text")]! as! String
UserDefaults.standard.set(notificationBody, forKey: "notifications")
---- 这仅打印最后一个通知-----
解决方案
每次使用此代码存储通知时,它都会覆盖当前值。这就是为什么您只收到最新消息的原因。您可以创建一个通知数组并将其存储在 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)")
}
}
推荐阅读
- google-play-services - 从 Google Play 安装后无法打开应用
- javascript - JavaScript 中的几种类型比较
- xml - XPath 验证元素是否不存在或不包含所需的值
- python - 从同一个表中获取具有级别的父子关系
- java - 骆驼:如何模拟具有两个端点的路线
- html - 如何以正确的方式在基于 AJAX 的网站上使用 AdSense?
- python - 无法从 python 函数返回具有所需顺序的列表
- python - seek() 接受 2 个位置参数,但给出了 3 个
- rust - 如何使用 cbindgen 返回和释放 Box
>? - jquery - 如何通过ajax调用将文件和字符串传递给控制器?