Firebase on ios is slow in retrieving data

∥☆過路亽.° 提交于 2019-12-02 09:46:56

The issue here is that Firebase works via asynchronous calls; your code will not work consistently because the code below the Firebase block may be called before the block completes.

You will need to start coding asynchronously and only perform actions on snapshot data after you know for sure it has been populated (inside the block)

       [[languagesRef queryOrderedByValue] observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {

            //at this point, firebase has loaded the snapshot
            //   so its available to work with

            [self.distanceMutableArray addObject:snapshot.key];

            for (NSInteger i = 0; i < self.distanceMutableArray.count; i++) {
                //do some stuff with the items in snapshot
            }

        }];

    //don't work with anything that was from the snapshot as it may have not been filled yet

However there's an issue as the code is using childAdded, so that will iterate over each item in the firebase node, so that code won't work either as it won't load the array correctly (yes we can fix that by populating the array during each loop).

The additional challenge here is that you need to retrieve data from Firebase based on the result of your first snapshot. Again, same situation exists; only perform actions on that retrieved data after you know for sure it has been retrieved.

One solution is to load in the entire dataset at one time and iterate over it (by value instead of added). If your data sets are smaller that works. However, for big datasets that can be too much.

[[languagesRef queryOrderedByValue] observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

  //at this point, firebase has loaded the snapshot
  //   so its available to work with and loaded with
  //everything in the node

  for ( FDataSnapshot *child in snapshot.children) {

    NSDictionary *dict = child.value;
    NSString *uid = child.key;

    [self.distanceMutableArray addObject:uid];

  }

  // now the array is loaded do something with it

}];

Another option is to change how your data is stored in firebase so you can retrieve data together so you dont have to make multiple observe calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!