swift - 存储在 Firestore 中的系统日期对象的行为将发生变化,您的应用程序可能会崩溃?

标签 swift firebase google-cloud-firestore

运行我的应用程序后,我在终端中得到以下输出。该应用程序不会崩溃。我到底应该把这段代码放在哪里?它到底有什么作用?

2018-08-16 09:45:05.414410-0400 Yubi[2652:1608362] 4.13.0 - [Firebase/Firestore][I-FST000001] The behavior for system Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK. To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:

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

With this change, timestamps stored in Cloud Firestore will be read back as Firebase Timestamp objects instead of as system Date objects. So you will also need to update code expecting a Date to instead expect a Timestamp. For example:

// old: let date: Date = documentSnapshot.get("created_at") as! Date // new: let timestamp: Timestamp = documentSnapshot.get("created_at") as! Timestamp let date: Date = timestamp.dateValue()

Please audit all existing usages of Date when you enable the new behavior. In a future release, the behavior will be changed to the new behavior, so if you do not follow these steps, YOUR APP MAY BREAK.

最佳答案

您应该在 appDelegate 中添加它,您要在其中添加配置。

FirebaseApp.configure()

let db = Firestore.firestore() 
let settings = db.settings 
settings.timestampsInSnapshotsEnabled = true 
db.settings = settings

通过将 areTimestampsInSnapshotsEnabled 设置为 true,它将保存时间戳而不是日期

因此,当您读取它时,它会返回时间戳,因此无论在您的代码中何处读取 Date,它现在都应该读取时间戳并按照建议将其转换为 Date 对象。

旧代码

 // old: This is old code returning Date object
    let date: Date = documentSnapshot.get("created_at") as! Date

应由新代码替换

 // new: This is new code returning Timestamp object
    let timestamp: Timestamp = documentSnapshot.get("created_at") as! Timestamp 
    let date: Date = timestamp.dateValue()

希望它能帮助您理解警告。您必须对现有代码进行更改以满足新准则,否则稍后会因类型不匹配而导致崩溃。

关于swift - 存储在 Firestore 中的系统日期对象的行为将发生变化,您的应用程序可能会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879443/

相关文章:

objective-c - 如何将此 ObjC 代码转换为 swift3?

javascript - Firebase 函数返回 "Response is not valid JSON object."

firebase - 如何从 Dart 中的 Cloud Firestore 获取随机文档(用于 Flutter)?

firebase - 如何从 Firestore 集合中获取所有唯一值?

dart - 如何修复 flutter 中 firestore 的事务错误?

ios - 刷新静态 View Controller

ios - 为图像添加视差效果

swift - xcschememanagement.plist 文件在 XCode 中有什么作用?我可以用 git 忽略它吗?

firebase - Stripe 订阅创建失败 - parameter_unknown : source

java - 如何将firestore中的日期时间存储与当前日期时间进行比较?