【问题标题】:How to get the date in Firebase如何在 Firebase 中获取日期
【发布时间】:2018-10-02 13:47:03
【问题描述】:

源码如下,

数据库:

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: ""
)

有人吗?

提前谢谢你。

【问题讨论】:

  • 请在您的问题中仅包含相关代码。阅读minimal reproducible example,然后阅读edit 您的问题,其中显示了演示问题的最小代码。
  • 您是否检查过 createdAt 属性实际上包含您的日期字符串?
  • for document... 循环中,如果您添加 print(document) 或在 var photoObject... 然后print(photoObject),输出是什么?您能否在问题中复制并粘贴一个文档或对象的输出(作为文本!),以便我们查看对象中存储的内容?
  • 我检查了 createdAt 属性包含 firebase 中的时间戳,而源代码属性包含字符串。 @andlin
  • photoObject:Photo(key: "x2q0Asfjn2S8FYr6fIvA", storeId: "", imgName: "locator/stores/egdupo/BitoysVulcanizingandTireShop_rJTM7alkTp_M6L.jpg", imageData: nil, title: "", description: "" , 排序: 1, uploadAt: "", createdAt: "") @Jay

标签: ios swift xcode firebase firebase-realtime-database


【解决方案1】:

来自 FireStore 文档

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

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

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

将 timestampsInSnapshots 设置为 true 将导致 Firestore 返回 时间戳值而不是日期,这样可以避免截断。注意 您还必须将任何使用 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
}

【讨论】:

  • 不走运,我尝试将 createdAt 设置为 Date,但它对我的代码不起作用。有什么解决办法吗?大帮助!会再试一次。希望一切顺利。
  • @AnneBernadette 您可能希望使用更新的代码更新您的问题 - 您强制它成为多个位置的字符串,这可能是问题的一部分。此外,您正在使用 JSON(根据我对您问题的评论),这不是必需的,可能会使问题进一步复杂化。
猜你喜欢
  • 2021-12-13
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多