Source code shown below,
Database:
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
]
Model:
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
}
Controller:
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
}
In Firebase we have field createdAt: (Timestamp)
Basically, when I run the codes in Xcode the Photo Storage fetch the createdAt from the firebase data but when it comes to Photo Object"self.photoCreatedAtLabel.text = "(photoObject.createdAt)" the date didn't shown. What is the possible missing in the codes? Please see attached of application for reference.
Edit: added a console printout of the photo object.
photoObject:Photo (
key: "x2q0Asfjn2S8FYr6fIvA",
storeId: "",
imgName: "locator/stores/egdupo/BitoysVulcanizingandTireShop_rJTM7alkTp_M6L.jpg",
imageData: nil,
title: "",
description: "",
sort: 1,
uploadedAt: "",
createdAt: ""
)
Anyone?
Thank you in advance.
From the FireStore docs
Currently, Firestore returns timestamp fields as Date but Date only supports millisecond precision, which leads to truncation and causes unexpected behavior when using a timestamp from a snapshot as a part of a subsequent query.
So if you want to use it, your code needs to handle it as a NSDate (Date) object. however, using the following code
let settings = Firestore.firestore().settings
settings.areTimestampsInSnapshotsEnabled = true
Setting timestampsInSnapshots to true will cause Firestore to return Timestamp values instead of Date, which avoids truncation. Note that you must also change any code that uses Date to use Timestamp instead.
In practice, assume we have a collection of documents and one of the fields in each document is called stamp; written like this
let now = Date()
let stamp = Timestamp(date: now)
self.db.collection("timestamps").document("test_stamp_0").setData( [
"stamp": stamp
])
to then read that stamp node and format it for output in a 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.