首页 > 解决方案 > 如何在 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
}

}

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


试试这个:假设我们有一个这样的 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) 对象。仅取决于您的用例。

时间戳 API


推荐阅读