从Firebase Swift检索信息的好方法 [英] Good way to Retrieve information from Firebase Swift

查看:145
本文介绍了从Firebase Swift检索信息的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的朋友正在与(新的)Firebase集成,迅速开展IOS项目。我们可以写入Firebase数据库,但我们在检索数据时遇到了问题。



我们有一个tableView控制器,我们希望从Firebase数据库填充表格。我们的数据库是这样组织的:

  root 
|
- 电影
| __ -Wjdkfdmlksdf(由Firebase制作的唯一ID)
|
| _Actors
| _A1 = ajkdfnadfdf
| _A2 = podifpadsfipasdip
| _Title =Mission Impossible
| _DirectedBy =Christopher McQuarrie
- 行动者
| _ -ajkdfnadfdf(由Firebase制作的唯一ID)
| _name:Tom Cruise
| _Birthday:xx / yy / zz

在这个项目中,我们创建了一个文件/类,它具有写入和从firebase中检索的方法。如果我们想从一个特定的视图控制器的Firebase中检索信息,我们只需要调用该类的一个特定的方法。



例如,这是class:

  func getListOfAllMovieIDs() - > [String] {
let ref = FIRDatabase.database()。reference();
var ListOfMovieIDS = [String](); $ MID $ b postDict = snapshot.value as![String:AnyObject]
(MID,$,$,$)$ b $ ref.child(Movies _)in postDict {
ListOfMovieIDS.append(MID);
}
$ b $}} {(error)in
print(error.localizedDescription)
}

return listOfMoviesIDS
}

我刚才在 tableViewController 中的 viewDidLoad()中描述过。但是,该方法什么都不返回。我们还调用了另一种方法来获取参与者的唯一IDS列表,并且不会返回任何内容。任何建议? Firebase以异步方式加载数据。因此,不是发送一个请求,而是等待一个响应,你发送一个请求,然后在某个时间点将被通知响应。



你可以很容易地看到这个,如果你在你的代码中放置一些放置良好的日志语句:
$ b $ pre $ func getListOfAllMovieIDs(){
let ref = FIRDatabase.database()。reference();
print(Before listener);
ref.child(Movies)。observeSingleEventOfType(.Value,withBlock:{(snapshot)in
print(Inside block);
})
print(听众后);

$ / code>

打印语句的顺序是:


在听众之前

听众


所以当你的函数退出的时候,数据还不可用。这不是一个错误,而是一个非常有意的选择。通过允许代码继续,该应用程序保持响应您的用户。大多数现代互联网都使用这种模式,所以通常最好接受它(尽管最初得到这个答案是非常棘手的)。

解决方法通常是改写你的代码。而不是说首先我们加载数据,然后我们做xyz,说我们开始加载数据,一旦我们得到它,我们做xyz。这就是为什么Firebase数据加载方法需要阻止:这包含数据可用时应该发生的xyz。



这个好的副作用是这个逻辑也适用于最初加载后可能会更新的数据。当你使用 objectEventOfType()时,你可以很容易地处理这种情况:开始同步数据,每当我们得到数据做xyz并且有一个应用程序来处理实时更新。 / p>

my friend and I are working on an IOS project on swift with (the new) Firebase integrated. We were able to write to the Firebase database, but we ran into problems in retrieve the data.

We have a tableView controller and we wish to populate the table from the Firebase database. Our database is organized like this:

root 
|  
- Movies
    |__ -Wjdkfdmlksdf (unique ID made by Firebase)
        |
        |_Actors
          |_A1 = ajkdfnadfdf
          |_A2 = podifpadsfipasdip
        |_Title = "Mission Impossible"
        |_DirectedBy = "Christopher McQuarrie"
-Actors
  |_ -ajkdfnadfdf (unique ID made by Firebase)
         |_name : "Tom Cruise"
         |_Birthday: xx/yy/zz

In the project, we made a file/class, which has methods that writes to and retrieves from firebase. If we want to retrieve information from Firebase for a particular view controller, we just call a particular method from that class.

For example, this is one of the methods in the class:

func getListOfAllMovieIDs() -> [String] {
     let ref = FIRDatabase.database().reference();
     var ListOfMovieIDS = [String]();
    ref.child("Movies").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
     let postDict = snapshot.value as! [String : AnyObject]
     for (MID, _) in postDict {
       ListOfMovieIDS.append(MID);
     }

    }) { (error) in
        print(error.localizedDescription)
    }

    return listOfMoviesIDS
}

we call this method that I just described above in the viewDidLoad() in the tableViewController. However, the method returns nothing. We also called another methods like to get the list of unique IDS for actors and that returns nothing either. Any suggestion?

解决方案

Firebase loads data asynchronously. So instead of firing a request and waiting for a response, you send a request and then at some point will be notified of the response.

You can easily see this if you put some well placed logging statements in your code:

func getListOfAllMovieIDs() {
    let ref = FIRDatabase.database().reference();
    print("Before listener");
    ref.child("Movies").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
      print("Inside block");
    })
    print("After listener");
}

The order of the print statements will be:

Before listener

After listener

Inside block

So by the time your function exits, the data isn't available yet. This is not a mistake, but a very intentional choice. By allowing the code to continue, the app stays responsive for your users. Most of the modern internet works with this model, so it's typically best to embrace it (although it's tricky to get the hang of initially).

The solution is usually to rephrase your code. Instead of saying "first we load the data, then we do xyz", say it as "we start loading the data, once we get it we do xyz". This is why the Firebase data loading methods take a block: this contains the "xyz" that should happen once the data is available.

A nice side-effect of this is that this logic also works great for data that may be updated after you initially loaded it. When you use objectEventOfType(), you can easily handle situations as "start synchronizing the data, whenever we get the data do xyz" and have an app that handles realtime updates.

这篇关于从Firebase Swift检索信息的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆