kanishka kanishka - 3 months ago 17
iOS Question

Unable to use userID as key while storing values in firebase

I am trying to save certain values for an user in firebase DB. The only way I can make sense of the data is by using the userID as the key. Here is what I am trying to achieve

https://firebaseDB/user_orders/userID -> List (Orders)

But, when I try to use user ID as the key, I am getting the error saying


2016-08-17 14:56:10.479 BetMe[4322:84427] *** Terminating app due to
uncaught exception 'NSUnknownKeyException', reason:
'[ setValue:forUndefinedKey:]:
this class is not key value coding-compliant for the key
3ISnq916LBdmmv7330ELByxCHV33.'


Here is my code snippet

let orderRef = rootRef.child("user_orders")

orderRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
//
if(!snapshot.hasChild(self.currentUser.uid))
{
orderRef.setValue("", forKey: self.currentUser.uid)
}

orderRef.child(self.currentUser.uid)
})

orderRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
for order in orders
{
//
if(!snapshot.hasChild(order.betId)){
orderRef.setValue(order.dictionaryRepresentation(), forKey: order.betId)
}

}
})


Please help me!

Answer

So i'm not to sure what order details you are recording but i've just made a blank one to save. I think the problem is that you're trying to save into a key that doesn't exist yet.

orderRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
        //
        if(!snapshot.hasChild(self.currentUser.uid))
        {
            let blankOrder = ["orderID": ""]
            //setting the uid as a path should create it when setValue is called
            orderRef.child(self.currentUser.uid).setValue(blankOrder)
        }
    })
Comments