1

I've been going around in circles about something that seems really simple, but I can't figure out it out. I simply want to read data from Firebase and save it in array so I can use it in my app. I know how to read the data as the following works for me to print out in the console:

 var ref = Firebase(url: "<MYFIREBASEURL>")

 ref.observeEventType(.ChildAdded, withBlock: { snapshot in

        print(snapshot.value.objectForKey("title"))

    })

I tried some of these approaches to save to an array, but I can't get it to work as it doesn't directly address my simpler question.

Adding Firebase data into an array

How to save data from a Firebase query

Thanks for your help!

0

2 Answers 2

4

This is how I am retrieving values and appending to array with Firebase. REF_POSTS is a url based reference to my posts object in Firebase. Remember that firebase objects are essentially dictionaries and you need to parse the data out of it and assign it to variables in order to use them.

    var posts = [Post]()// put this outside of viewDidLoad

    //put the below in viewDidLoad
    DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
        print(snapshot.value)  
        self.posts = []
        if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
            for snap in snapshots {
                if let postDict = snap.value as? Dictionary<String, AnyObject> {
                    let key = snap.key
                    let post = Post(postKey: key, dictionary: postDict)
                    self.posts.append(post)
                } 
            }
        }
        self.postTableView.reloadData() 
    })
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing your approach.
4

I figured it out after sleeping on it. Posting here to make it easier for the next person to figure out.

 // Class variables
 var ref = Firebase(url: "https://<MYFIREBASEURL>")
 var titlesArray = [String]()

 // Under viewDidLoad

 // "events" is the root, and "title" is the key for the data I wanted to build an array with.
 let titleRef = self.ref.childByAppendingPath("events")
    titleRef.queryOrderedByChild("title").observeEventType(.ChildAdded, withBlock: { snapshot in

        if let title = snapshot.value["title"] as? String {
            self.titlesArray.append(title)

            // Double-check that the correct data is being pulled by printing to the console.
            print("\(self.titlesArray)")

            // async download so need to reload the table that this data feeds into.
            self.tableView.reloadData()
        }
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.