2017-08-01 143 views
0

請任何人告訴我如何包括快照鍵值和兒童價值,我已經附加到我的數組(忘記包括它,現在記得我必須)...除了那些真的我當我嘗試解決我自己的問題時,無法理解,通過使用此方法首先測試值:print(rooms.popFirst().key!)我的數據庫值的一半得到了nil的值?如果我不包括這種方法,一切都很好,但如果你無法想象,但我真的希望你的建議或建議,以獲得所有數據與自己的關鍵價值... 這是我的代碼到目前爲止:如何包含firebase快照鍵值? [Swift]

Database.database().reference().child("rooms").observe(.value, with: { (snapshot) in 
     print() 

     var rooms = snapshot.value as! [String:AnyObject] 

     for(_,value) in rooms { 

      if (rooms.popFirst()?.key) != nil{ 

       let title = value["title"] as? String 
       let description = value["description"] as? String 
       let roomPictureUrl = value["Room Picture"] as? String 
       let longitude = value["Longtitude"] as? String 
       let latitude = value["Latitude"] as? String 
       let dateFrom = value["Date From"] as? String 
       let dateTo = value["Date To"] as? String 
       let owner = value["Owner"] as? String 

       let myRooms = Room(roomID: "XXX",title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!) 

       //print(rooms.popFirst()?.key) 
       self.rooms.append(myRooms) 
       self.tableView.reloadData() 



      } 
     } 
    }) 

回答

1

試試這個:

Database.database().reference().child("rooms").observe(.value, with: { (snapshot) in 

    var rooms = snapshot.value as! [String:AnyObject] 
    let roomKeys = Array(rooms.keys) 

    for roomKey in roomKeys { 

      guard 

       let value = rooms[roomKey] as? [String:AnyObject] 

      else 
      { 
       continue 
      } 

      let title = value["title"] as? String 
      let description = value["description"] as? String 
      let roomPictureUrl = value["Room Picture"] as? String 
      let longitude = value["Longtitude"] as? String 
      let latitude = value["Latitude"] as? String 
      let dateFrom = value["Date From"] as? String 
      let dateTo = value["Date To"] as? String 
      let owner = value["Owner"] as? String 

      let myRooms = Room(roomID: "XXX",title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!) 

      print(roomKey) 
      self.rooms.append(myRooms) 
      self.tableView.reloadData() 



     } 
    } 
}) 
0

要想從快照鍵可以使用下面的代碼行,它會給你造成像-> Kqwewsds12 -> your child Details

let dictValues = [String](snapshot.keys) 

      print(dictValues[0]) //Output -- Kqwewsds12