使用Swift 3.0从随机子路径中检索Firebase中的数据

时间:2016-11-22 00:10:27

标签: swift firebase firebase-realtime-database

我正在尝试从使用现有字符串数组作为参考的随机文件夹的目录中检索项目数组

我的数据如下:

 Items
  - RandomID
    -title : "text"
    -subtitle: "text"

到目前为止,这是我尝试过的,但它无效:

var array = [String]() //array to use as reference
var returnedItems = [Item]() //array of item objects

func retrieveData()
 {
     for i in array
      {
        let ref = main.child("Items")
        let query = ref.queryEqual(toValue: i)
        query.observeSingleEvent(of: .value, with: { (snapshot) in

            let item = Item!

            if snapshot.hasChild("title")
             {
               item.title = (snapshot.value as! NSDictionary)["title"] as? String
             }
            if snapshot.hasChild("subtitle")
             {
               item.subtitle = (snapshot.value as! NSDictionary)["subtitle"] as? String
             }

            returnedItems.append(item)
            self.tableView.reloadData()
            print("Item: \(self.returnedItems.map { $0.title})")

         })
     }
 }

任何帮助将不胜感激! 在此先感谢;)

1 个答案:

答案 0 :(得分:0)

如果您正在尝试检索所有子项,则可以使用单个侦听器(以this example in the documentation为模型):

var array = [String]() //array to use as reference
var returnedItems = [Item]() //array of item objects

func retrieveData() {
    query.observeSingleEvent(of: .value, with: { (snapshot) in
        for child in snapshot.children {
            let item = Item!
            if child.hasChild("title") {
                item.title = (snapshot.value as! NSDictionary)["title"] as? String
            }
            if child.hasChild("subtitle") {
                item.subtitle = (snapshot.value as! NSDictionary)["subtitle"] as? String
            }

            returnedItems.append(item)
            self.tableView.reloadData()
            print("Item: \(self.returnedItems.map { $0.title})")
        })
    }
    // returnedItems will still be empty here, since the data hasn't
    // been loaded yet. See the note after this code snippet.
}

但请注意,读取数据仍会在此处异步发生,因此returnedItems返回时retrieveData仍为空。