首页 > 解决方案 > 如何在 Firebase 中获取日期

问题描述

源代码如下图,

数据库:

static func insertErrorLog(moduleName: String, message: String) {
    let dateToday = Date()
    let timestamp = Int(Date().timeIntervalSince1970)

    let db = Firestore.firestore()

    let docData: [String: Any] = [
        KDB.Fields.moduleName : moduleName,
        KDB.Fields.message : message,
        KDB.Fields.createdAt : dateToday
    ]

模型:

var uploadedAt: String = ""
var createdAt: String = ""

init(document: DocumentSnapshot) {
    self.key = document.documentID

    let json = JSON(document.data())

    self.storeId = json[KDB.Fields.storeId].stringValue
    self.imgName = json[KDB.Fields.imgName].stringValue
    self.title = json[KDB.Fields.title].stringValue
    self.description = json[KDB.Fields.description].stringValue
    self.sort = json[KDB.Fields.sort].intValue
    self.uploadedAt = json[KDB.Fields.uploadedAt].stringValue
    self.createdAt = json[KDB.Fields.createdAt].stringValue
}

init(key: String, storeId: String, imgName: String, title: String, description: String, sort: Int, uploadedAt: String, createdImageAt: String = "") {
    self.key = key
    self.storeId = storeId
    self.imgName = imgName
    self.title = title
    self.description = description
    self.sort = sort
    self.uploadedAt = uploadedAt
    self.createdAt = createdImageAt
}

控制器:

    query.getDocuments { (querySnapshot, error) in
        if let error = error {
            SpeedLog.print("Error: \(error.localizedDescription)")
        } else {
            var loop = 1
            for document in (querySnapshot?.documents)! {
                SpeedLog.print("documentDATA:\(document.data())")
                var photoObject = Photo(document: document)
                SpeedLog.print("photoObject:\(photoObject)")

                if (!photoObject.imgName.isEmpty) {
                    let storagePath = "\(photoObject.imgName)"
                    SpeedLog.print("Photo storagePath: \(storagePath)")

                    let storage = Storage.storage()
                    let storageRef = storage.reference()
                    let imageRef = storageRef.child(storagePath)

                    imageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
                        if let error = error {
                            SpeedLog.print("Photos download image error documentID:\(document.documentID) : \(error.localizedDescription)")
                        } else {
                            photoObject.imageData = UIImage(data: data!)
                            self.photos.append(photoObject)

                            if loop == 1 {
                                self.imageView.image = photoObject.imageData!
                                self.photoTitleLabel.text = "\(photoObject.title)"

                                    self.photoCreatedAtLabel.text = "\(photoObject.createdAt)"
                                    self.photoCreatedAtTitleLabel.isHidden = false
                                //}
                            }
                        }
                        self.collectionView.reloadData()
                        loop += 1
                    }
                }
            }
        }
    }
}

extension PhotoGalleryViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photos.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellPhotoGallery", for: indexPath) as! PhotoGalleryCollectionViewCell

    configureCell(cell, atIndexPath: indexPath)

    return cell
}

func configureCell(_ cell: PhotoGalleryCollectionViewCell, atIndexPath indexPath: IndexPath) {

    let photo = photos[indexPath.row]

    if let image = photo.imageData {
        cell.imageView.image = image
    }
    photoLabel.text = photo.title
    photoCreatedAtLabel.text = photo.createdAt
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let photo = photos[indexPath.row]

    if let image = photo.imageData {
        imageView.image = image
    }
    photoLabel.text = photo.title
    photoCreatedAtLabel.text = photo.createdAt
}

在 Firebase 中,我们有字段 createdAt: (Timestamp)

基本上,当我在 Xcode 中运行代码时,照片存储从 firebase 数据中获取 createdAt,但是当涉及到 Photo Object"self.photoCreatedAtLabel.text = "(photoObject.createdAt)" 时,日期没有显示。什么是代码中可能缺少吗?请参阅应用程序附件以供参考。

编辑:添加了照片对象的控制台打印输出。

photoObject:Photo (
   key: "x2q0Asfjn2S8FYr6fIvA", 
   storeId: "", 
   imgName: "locator/stores/egdupo/BitoysVulcanizingandTireShop_rJTM7alkTp_M6L.jpg", 
   imageData: nil, 
   title: "", 
   description: "", 
   sort: 1, 
   uploadedAt: "", 
   createdAt: ""
)

上传日期 2 of 2

任何人?

先感谢您。

标签: iosswiftxcodefirebasefirebase-realtime-database

解决方案


来自 FireStore 文档

目前,Firestore 以 Date 形式返回时间戳字段,但 Date 仅支持毫秒精度,当使用快照中的时间戳作为后续查询的一部分时,这会导致截断并导致意外行为。

所以如果你想使用它,你的代码需要把它当作一个NSDate(Date)对象来处理。但是,使用以下代码

let settings = Firestore.firestore().settings
settings.areTimestampsInSnapshotsEnabled = true

将 timestampsInSnapshots 设置为 true 将导致 Firestore 返回 Timestamp 值而不是 Date,从而避免截断。请注意,您还必须将任何使用 Date 的代码更改为使用 Timestamp。

在实践中,假设我们有一个文档集合,每个文档中的一个字段称为邮票;写成这样

let now = Date()
let stamp = Timestamp(date: now)
self.db.collection("timestamps").document("test_stamp_0").setData( [
   "stamp": stamp
])

然后读取该标记节点并将其格式化以在 UI 中输出

//read the document
if let stamp = document.get("stamp") {
    let title = document.documentID
    let ts = stamp as! Timestamp //force downcast stamp to a Timestamp cause' that's what it is.
    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) //prints test_stamp_0, 2018-10-03 08:00:00 -0400
}

推荐阅读