ios - 如何在 iOS 中使用 FieldValue.serverTimestamp() 作为模型类 - swift
问题描述
我使用 Firestore 作为数据库,现在我想在用户注册时存储服务器时间戳。这个问题与Android相反
FieldValue.serverTimestamp()
这是模型类
struct NotificationModel: Identifiable, Codable {
var id: String? = nil
var title: String?
var body: String?
var timestamp: Date?
init(title: String, body: String, timestamp: Date) {
self.title = title
self.body = body
self.timestamp = timestamp
}
}
我想在我的模型类中使用这个时间戳。
我怎样才能实现这样的目标?
.document(ID).collection("notifications").order(by: "timestamp", descending: true).addSnapshotListener { (snapshot, error) in
这是我decode
记录Firestore
到 Json的整个代码
func readUserNotifications<T: Decodable>(from collectionReference: FIRCollectionReference, get userId: String, returning objectType: T.Type, fromType collectionCell: FIRCollectionCell, completion: @escaping ([T], _ sucess: Bool) -> Void) {
collectionReferences(to: collectionReference).document(userId).collection("notifications").order(by: "timestamp", descending: true).addSnapshotListener { (snapshot, error) in
var objectsAppend = [T]()
if let error = error {
print(error.localizedDescription)
}
guard let snapshot = snapshot else {
print("Doesn't have snapshot")
return
}
do {
for document in snapshot.documents {
//print(try document.decode(as: NotificationModel.self))
let object = try document.decode(as: objectType.self, includingId: true)
objectsAppend.append(object)
}
if objectsAppend.isEmpty {
objectsAppend.removeAll()
completion(objectsAppend, false)
} else {
completion(objectsAppend, true)
}
} catch {
print(error)
}
}
}
这是我的decode
功能,那里有错误
extension DocumentSnapshot {
func decode<T: Decodable>(as objectType: T.Type, includingId: Bool = true) throws -> T {
var documentJson = data()
if includingId {
documentJson["id"] = documentID
}
let documentData = try JSONSerialization.data(withJSONObject: documentJson, options: [])
let decodedObject = try JSONDecoder().decode(objectType, from: documentData)
return decodedObject
}
}
解决方案
试试这个:假设我们有一个这样的 Firestore 结构(如 Firestore 控制台所示)
timestamps
stamp_0
stamp: September 18, 2018 at 8:00:00 AM UTC-4
stamp_1
stamp: September 18, 2018 at 8:01:00 AM UTC-4
stamp_2
stamp: September 18, 2018 at 8:02:00 AM UTC-4
我们想读取时间戳并将密钥和格式化的时间戳打印到控制台。
self.db.collection("timestamps").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
if let stamp = document.get("stamp") {
let title = document.documentID
let ts = stamp as! Timestamp
let aDate = ts.dateValue()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let formattedTimeZoneStr = formatter.string(from: aDate)
print(title, formattedTimeZoneStr)
}
}
}
}
输出是
stamp_0 2018-09-18 08:00:00 -0400
stamp_1 2018-09-18 08:01:00 -0400
stamp_2 2018-09-18 08:02:00 -0400
这就是您获取时间戳数据的方式。
可以通过多种方式将其存储在模型类中,具体取决于您要对其执行的操作:可以将其存储为格式化的时间戳字符串(如我的回答所示),或者 Firestore Timestamp 对象或 Date ( NSDate) 对象。仅取决于您的用例。
推荐阅读
- flutter - 在不同的屏幕上显示自定义容器
- java - 正则表达式查找单引号文本java
- google-chrome-extension - Google Chrome 扩展程序中未捕获的 ReferenceError
- html - GitHub Pages 不提取图像
- vba - 无法单击框架内的按钮 - VBA Selenium ChromeDriver
- ios - 我应该使用 UIDocument 来处理已保存到磁盘的 PDF 文件吗?
- python - Tkinter 窗口打开时没有标签
- python - 如何在 Python 中创建浮动 GUI 菜单列表?
- rest - 我应该为批量 CRUD 操作 REST 创建单独的端点吗?
- python - 提取大写之前的元素