如何在iOS中使用FieldValue.serverTimestamp()作为Model类 - swift

问题描述 投票:0回答:1

我使用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到Json的Firestore文件的完整代码

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
}

}

ios swift firebase google-cloud-firestore
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.