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

时间:2018-09-17 16:18:10

标签: ios swift firebase google-cloud-firestore

我将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

这是我decodeFirestore到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
}

}

1 个答案:

答案 0 :(得分:1)

尝试以下操作:假设我们有一个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对象或日期(NSDate)对象。只是取决于您的用例。

Timestamp API