Charles Jr
Charles Jr

Reputation: 9129

Firebase query with variables in Swift

I'm trying to find specific user images from my Firebase data set I'm naming the group users with unique display names as children and those children with keys of name, lowerCaseName, UID, and Image.
enter image description here

Is there anyway I can query through users as a variable in order to get to images?? I'm thinking http://firebase.com/users/%diplaynames/image but not sure.

Upvotes: 1

Views: 909

Answers (3)

Jay
Jay

Reputation: 35657

A couple of thoughts:

While there is nothing wrong with your structure, you may want to consider changing the node names from the users name to a firebase auto generated ID.

users
   user_0
    name: Charles
    image: some image
   user_1
    name: Zaddy
    image: another image

Sometimes data will change, so for example say Charles wants to be called Charlie. To make that change you would have to delete the Charles node*, re-add it, and then update every node that refers back to Charles. If you name it with an auto-generated id (or the uid; best practice) user_0, then just update the name: "Charlie" and everything else falls into place.

*The child name: and the node name can certainly be the same or different, so this is a situational example.

To get Charles' image (assuming it's base64 encoded) and you want to add it to an imageView

    let ref = Firebase(url:"https://your_app.firebaseio.com/users")
    ref.queryOrderedByChild("name").queryEqualToValue("Charles")
       .observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in

        //snapshot will contain the child key/value pairs
        let base64EncodedString = snapshot.value.objectForKey("image")
        let imageData = NSData(base64EncodedString: base64EncodedString as! String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
        let decodedImage = NSImage(data:imageData!)
        self.myImageView.image = decodedImage

    })

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599001

In Firebase, you cannot retrieve a subset of the properties of a node. Either a node is retrieved, or it isn't.

If you have a use-case where you need to retrieve just the images, you should store a top-level node that has just those images.

userImages
  Charles: base64data
  Zach: base64data

Upvotes: 0

BHendricks
BHendricks

Reputation: 4493

What is your Firebase base url? You should be querying the path that looks something like:

https://<APP ID HERE>.firebaseio.com/

So you're initialization of Firebase should look like:

let fire = Firebase(url: "https://<APP ID HERE>.firebaseio.com/users/<DISPLAYNAME>/image")

Alternatively, you could do:

let fire = Firebase(url: "https://<APP ID HERE>.firebaseio.com")
let imageRef = fire.childByAppendingPath("users").childByAppendingPath("<DISPLAYNAME>).childByAppendingPath("image")

Upvotes: 1

Related Questions