cisc0
cisc0

Reputation: 126

Check if string in firebase data exist

I would like to check if in my database there is the same string that I write in text field. I tried this:

let s = textField?.text!.lowercased()

    DataService.ds.MSGS_DB_REF_KEY1.queryOrdered(byChild: "livelli").observe(.value, with: { snapshot in
        for item in snapshot.children{
            if (s?.contains(item as! String))!{

            }
        }

    })

But this give me the error, because obviously string and FIRDataSnapshot are different things.How could I solve this?

enter image description here

enter image description here

Upvotes: 0

Views: 698

Answers (2)

Peter Tao
Peter Tao

Reputation: 1708

Convert the item to a FIRDataSnapshot and get the value.

let s = textField?.text!.lowercased()

DataService.ds.MSGS_DB_REF_KEY1.queryOrdered(byChild: "livelli").observe(.value, with: { snapshot in
    for item in snapshot.children{
        let itemSnap = item as! FIRDataSnapshot
        for child in itemSnap.children {
            childSnap = child as! FIRDataSnapshot
            if let firebaseVal = childSnap.childSnapshot(forPath: "text").value as? String {
                if s?.contains(firebaseVal.lowercased()){

                }
            }
        }
    }

})

Upvotes: 2

McCygnus
McCygnus

Reputation: 4215

You need to get the value out of the FIRDataSnapshot:

for item in snapshot.children{
    if let itemValue = (item as? FIRDataSnapshot).value as? String, let s = s, s.contains(itemValue){

    }
}

Also, don't force unwrap if you don't have to. Safely unwrap them so that you don't risk crashes if something changes in the future.

Upvotes: 2

Related Questions