Ruc*_*ore 5 ios firebase swift4 codable
我正在尝试将我的数据映射到模型。我在其中使用 Firestore 快照侦听器来获取数据。在这里,我正在获取数据并映射到“用户”模型;
do{
let user = try User(dictionary: tempUserDic)
print("\(user.firstName)")
}
catch{
print("error occurred")
}
Run Code Online (Sandbox Code Playgroud)
这是我的模型:
struct User {
let firstName: String
// var lon: Double = 0.0
// var refresh:Int = 0
// var createdOn: Timestamp = Timestamp()
}
//Testing Codable
extension User: Codable {
init(dictionary: [String: Any]) throws {
self = try JSONDecoder().decode(User.self, from: JSONSerialization.data(withJSONObject: dictionary))
}
private enum CodingKeys: String, CodingKey {
case firstName = "firstName"
}
}
Run Code Online (Sandbox Code Playgroud)
如果我错了请纠正我。
崩溃是因为我在数据中获取“时间戳”。
从监听器获取的数据:
用户词典:
[\"firstName\": Ruchira,
\"lastInteraction\": FIRTimestamp: seconds=1576566738 nanoseconds=846000000>]"
Run Code Online (Sandbox Code Playgroud)
如何将“时间戳”映射到模型?
尝试过“CodableFirstore” https://github.com/alickbass/CodableFirebase
我通过将FIRTimestamp字段转换为Double(秒)解决了这个问题,以便JSONSerialization可以相应地解析它。
let items: [T] = documents.compactMap { query in
var data = query.data() // get a copy of the data to be modified.
// If any of the fields value is a `FIRTimestamp` we replace it for a `Double`.
if let index = (data.keys.firstIndex{ data[$0] is FIRTimestamp }) {
// Convert the field to `Timestamp`
let timestamp: Timestamp = data[data.keys[index]] as! Timestamp
// Get the seconds of it and replace it on the `copy` of `data`.
data[data.keys[index]] = timestamp.seconds
}
// This should not complain anymore.
guard let data = try? JSONSerialization.data(
withJSONObject: data,
options: .prettyPrinted
) else { return nil }
// Make sure your decoder setups the decoding strategy to `. secondsSince1970` (see timestamp.seconds documentation).
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return try? decoder.decode(T.self, from: data)
}
// Use now your beautiful `items`
return .success(items)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1811 次 |
| 最近记录: |