我在firebase中有这种形式的数据,我需要显示设施及其相应的预订,以便我可以在模型类中解析这些数据。我是解析的新手。 我已经完成但是我无法在FacilityBooking模型类中解析facilityXXXXXXXX。然后我再次需要在另一个预订模型类中解析预订。
struct Facilities_id {
let key: String
var facilities: FacilityBooking
let ref: FIRDatabaseReference
init(snapshot: FIRDataSnapshot) {
key = snapshot.key
ref = snapshot.ref
let snapshotValue = snapshot.value as! [String: AnyObject]
}
}
这是我用来获取数据的代码
let ref = FIRDatabase.database().reference(withPath: "facility")
ref.observe(.value, with: { snapshot in
// 2
var facility: [Facilities_id] = []
// 3
for code in snapshot.children {
// 4
let facilityObj = Facilities_id(snapshot: code as! FIRDataSnapshot)
facility.append(facilityObj)
}
// 5
self.facility_id_Arr = facility
print("facitlities ---",self.facility_id_Arr)
})
答案 0 :(得分:2)
您需要先以这种方式更改struct
。
struct Facilities_id {
let key: String
let facilityId: String
var facilities: [FacilityBooking]
let desc: String
let name: String
let ref: FIRDatabaseReference
init(snapshot: FIRDataSnapshot, id: String, dictionary: [String:Any]) {
key = snapshot.key
ref = snapshot.ref
facilityId = id
desc = dictionary["desc"] as? String ?? ""
name = dictionary["name"] as? String ?? ""
let bookingDic = dictionary["booking"] as? [String:Any] ?? [String:Any]()
facilities = bookingDic.map { FacilityBooking(bookingId: $0, dictionary: $1 as? [String:Any] ?? [:]) }
}
}
struct FacilityBooking{
let bookingId: String
let customer: String
let price: Int
let duration: Int
let uid: String
init(bookingId: String, dictionary: [String:Any]) {
bookingId = bookingId
customer = dictionary["customer"] as! String
price = dictionary["price"] as! Int
duration = dictionary["duration"] as! Int
uid = dictionary["uid"] as! String
}
}
现在只需创建Facilities_id
。
let ref = FIRDatabase.database().reference(withPath: "facility")
ref.observe(.value, with: { snapshot in
var facility: [Facilities_id] = []
for code in snapshot.children {
let snapShot = code as! FIRDataSnapshot
let value = snapShot.value as? [String:Any] ? [:]
let facilityArray = value.map {
Facilities_id(snapshot: snapShot, id: $0, dictionary: $1 as? [String:Any] ?? [:])
}
facility += facilityArray
}
self.facility_id_Arr = facility
print("facitlities ---",self.facility_id_Arr)
})