0

I am trying to query the most popular hashtags in my database. The most popular hashtag has the most posts. First, this is how my Hashtags database looks like

Hashtags
    L firstHashtag
        L post1: true
        L post2: true
        L post3: true
        L post_count: 3
    L secondHashtag
        L post4: true
        L post5: true
        L post6: true
        L post7: true
        L post8: true
        L post_count: 5
    L thirdHashtag
        L post9: true
        L post_count: 1

I query their order based on their post count and fetch the 8 most popular hashtags like this:

func observePopularTags(completion: @escaping (String) -> Void) {
    REF_HASHTAG.queryOrdered(byChild: "post_count").queryLimited(toLast: 8).observe(.childAdded, with: {
        snapshot in
        completion(snapshot.key)
    })
}

Then I add them to an empty array

var hashtags: [String] = []

After that I call a function to observe & insert the popular hashtags in the array

func getHashtags() {
    Api.HashTag.observePopularTags { (name) in
        let hashtag = "#" + name
        // This works, it prints out each popular hashtag
        print(hashtag)
        self.hashtags.append(hashtag)
    }
    // When I print out the whole array, it prints an empty array.
    print("Hashtags: ", hashtags)
}

I call this function in the viewDidLoad method. However, when I print the array, it prints it out as an empty array. Why is this happening?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
vApp
  • 249
  • 1
  • 6
  • 18

1 Answers1

1

Data is loaded from Firebase asynchronously. When you print hashtags it hasn't completed loading yet. Any code that requires access to the data from Firebase must be inside the completion handler. So:

func getHashtags() {
    Api.HashTag.observePopularTags { (name) in
        let hashtag = "#" + name
        // This works, it prints out each popular hashtag
        print(hashtag)
        self.hashtags.append(hashtag)
        print("Hashtags: ", hashtags)
    }
}

Also see this answer I gave earlier today.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Okay thanks. I am trying to put the value in that array into a table view cell.The problem is that the table view runs before the data is loaded into the array. So what should I do in this case? – vApp Nov 22 '17 at 05:30