簡體   English   中英

如何在 Firebase 中獲取日期

[英]How to get the date in 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

任何人?

先感謝您。

來自 FireStore 文檔

目前,Firestore 將時間戳字段返回為日期,但日期僅支持毫秒精度,這會導致截斷並在將快照中的時間戳用作后續查詢的一部分時導致意外行為。

所以如果你想使用它,你的代碼需要將它作為一個 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM