2017-07-25 136 views
0

我的JSON是這樣的:火力地堡值獲取孩子的名字,將其取下

users 
    username1: "WWOdh96Yr3Qs4N3GWDVq3OlQFfB2" 
    username2: "RJ6PztTLmsg222oUygWHtWpVHdg1" 

我想通過他們的關鍵是(auth.uid)獲得「用戶名1」!如果它發現我想刪除它,所以刪除後它將看起來像這樣:

users 
    username2: "RJ6PztTLmsg222oUygWHtWpVHdg1" 

self.ref.child("users").queryOrderedByValue().queryEqual(toValue: user?.uid).observe(.value, with: { snapshot in 

          if snapshot.exists() { 

           print("\(snapshot.value)") 
           snapshot.ref.child(snapshot.value as! String).removeValue() // this deleting every thing which is WRONG! 



          } else{ 

           print("Not found--") 

          } 
          self.ref.removeAllObservers() 
         }) 
        } 

此代碼刪除用戶中的所有內容。我只想刪除特定的用戶。

回答

2

首先,我的方法是,如果我想在1時刻查詢1個值,就像你在做,我做一個observeSingleEvent(這是最好的方法?)。但爲了解決你的問題,你忘了添加你的「用戶」路徑。下面的代碼是更安全的使用,因爲你強迫展開(這是不推薦這種情況下):

let dataRef = self.ref.child("users") 
dataRef.keepSynced(true) 
     if let usersUID = Auth.auth().currentUser?.uid{ 
    dataRef.child("users").queryOrderedByValue().queryEqual(toValue: usersUID).observeSingleEvent(.value, with: { snapshot in 
     print(snapshot) 
     let values = snapshot.value as? NSDictionary 
     for (key, value) in values{ 
     print(value) // does this print the uid? 
     print(key) // or this one? 

      self.ref.child("users/\(key)").removeValueWithCompletionBlock({ (err, ref) in 
       if err != nil { 
        print(err) 
       } else { 
        print(ref) 
        print("Removed") 
       } 
      }) 
     } 
    }) 
    } 

嘗試添加這個,右後打印(快照)

+0

謝謝!但你能告訴我怎麼能在這種情況下使用「observeSingleEvent」?編輯你的答案,完整的代碼將被讚賞和接受 – Sam

+0

@Sam我更新了它,它應該工作,雖然我沒有測試它 –

+0

我感到困惑,如果你能解釋發生了什麼,請https://i.gyazo.com /15dc03d6245cad3114120a680e422734.png我已經提到照片中發生了什麼。任何想法? – Sam