2017-02-20 91 views
0

enter image description here數據從火力

我有數據以這種形式火力的我需要顯示設備及其相應的預約我怎麼能解析解析該數據模型class.I是新的模型類解析。 這我已經做了,但我無法在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

你在分析新的,但你仍然可以給一個嘗試.. –

+0

我試過,但沒有成功 結構Facilities_id { 讓關鍵:字符串 讓裁判:FIRDatabaseReference 的init(快照:FIRDataSnapshot) {key = snapshot.key ref = snapshot.ref let snapshotValue = snapshot.value as! [String:AnyObject] } } –

+0

@RahulGupta向我們展示您嘗試過的。 –

回答

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) 
})