简体   繁体   中英

Check if Key exists in Firebase

I have been searching for an answer and could not find it.

I am using Swift 3. I have a path, let's say firebase/products, and I want to see if a specific product has a key "MainImage". So naturally I'd do something like

Database.Child("Products").Child("ProductID").HasChild("MainImage")

But there's no method like "HasChild", or "Exists" or anything similar I could find out. Does anyone have the solution for this ?

There is no method that can check for that, you are going to listen to that child and if it has a nil value, then it does not exist.

var ref = FIRDatabase.database().reference()

let ProductID = 64646477343

let  requestListenRefo = ref.child("Products/\(ProductID)/MainImage")

    requestListenRefo.observe(FIRDataEventType.value, with: { (snapshot) in  

       let value = snapshot.value as? String

        if(value == nil)
        {
            // doesn't exist
        }

     })

There is a way to check existence of the snapshot using snapshot.exists()

Swift

dbRef = FIRDatabase.database().reference()

dbRef.child("Users/user1").observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.exists(){
        print("user1 exists")
    }else{
        print("user1 exists doesn't exists")
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM