我正在从Firebase数据库中检索对象,我需要将它们转换为自定义结构类对象
类别:
struct Request {
var Address: String!
var Position: Position!
var RequestID: String!
var Status: String!
}
从我的Firebase数据库获取快照的功能:
self.ref.child("requests").observe(.childAdded, with: { snapshot in
//I need to cast this snapshot object to a new Request object here
let dataChange = snapshot.value as? [String:AnyObject]
print(dataChange)
})
我怎样才能完成这项工作?
答案 0 :(得分:4)
有几件事。 Firebase没有对象 - 它是一个JSON结构。当你像这样得到snapshot.value时:
let dataChange = snapshot.value as? [String:AnyObject]
[String:AnyObject]将数据定义为Dictionary。
然后,您可以像这样访问dataChange中的键:值对
let address = dataChange["address"]
和
let position = dataChange["position"]
从那里你可以创建新对象并在闭包中填充它们(例如将它们添加到数组中)或者在对象中放入更多智能并传递字典并让对象填充自己。
以下是伪代码,但它提供了以下过程:
//create the object and populate it 'manually'
self.ref.child("requests").observe(.childAdded, with: { snapshot in
let dataChange = snapshot.value as? [String:AnyObject]
let aRequest = Request()
aRequest.address = dataChange["address"]
aRequest.position = dataChange["position"]
self.requestArray.append(aRequest)
})
或
Class Request {
var address = ""
var position = ""
func initWithDict(aDict: [String: AnyObject]) {
self.address = aDict["address"]
self.position = aDict["position"]
}
}
//let the object populate itself.
self.ref.child("requests").observe(.childAdded, with: { snapshot in
let dataChange = snapshot.value as? [String:AnyObject]
let aRequest = Request(initWithDict: dataChange)
self.requestArray.append(aRequest)
})
答案 1 :(得分:1)
如果您的结构中包含很多字段,则更容易执行以下操作(Swift 4 +):
struct Request: Decodable {
var Address: String
var RequestID: String
var Status: String
}
self.ref.child("requests").observe(.childAdded, with: { snapshot in
guard let data = try? JSONSerialization.data(withJSONObject: snapshot.value as Any, options: []) else { return }
let yourStructObject = try? JSONDecoder().decode(Request.self, from: data)
}