使用Firebase填充数组

时间:2016-10-21 09:53:01

标签: arrays swift firebase firebase-realtime-database

现在仍然想在Swift中用firebase学习我的firebasics。我在使用firebase填充数组时遇到问题。该数组将用于填充collectionView。我现在的代码是:

override func viewDidLoad() {
    super.viewDidLoad()

    self.collectionView!.register(locationCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    let nib: UINib = UINib(nibName: "locationCollectionViewCell", bundle: nil)
    self.collectionView!.register(nib, forCellWithReuseIdentifier: reuseIdentifier)


    let flowLayout = UICollectionViewFlowLayout()
    flowLayout.itemSize = CGSize(width: 200, height: 200)
    flowLayout.scrollDirection = .horizontal
    self.collectionView?.collectionViewLayout = flowLayout

    myFirebaseFunc()

}

func myFirebaseFunc () {
    let locationRef = FIRDatabase.database().reference().queryOrdered(byChild: "Location")
    locationRef.observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists() {
            var sorted = ((snapshot.value! as AnyObject).allValues as NSArray).value(forKey: "name") as! NSArray
            sorted = sorted[0] as! NSArray
            for element in sorted {
                let m = MyStruct(name: element as! String)
                self.myArray.append(m)
            }
            print(self.myArray) //array is correctly populated
            DispatchQueue.main.async{
                self.collectionView?.reloadData()
            }
        }
    })
    print(self.myArray) //array is suddenly empty

}

JSON数据:

{
  "Location" : [ {
    "address" : "602 Pacific Coast Hwy, Huntington Beach, CA 92648",
    "hours" : "Sun 8am-8pm, Mon - Sat 8am-9pm",
    "name" : "Huntington Beach",
    "phoneNumber" : "(714) 536-TACO(8226)"
  }, {
    "address" : "3014 W Balboa Blvd, Newport Beach, CA 92663",
    "hours" : "Sun 8am-8pm, Mon - Sat 8am-9pm",
    "name" : "Newport Beach",
    "phoneNumber" : "(949) 723-TACO(8226)"
  } ]
}

使用调试器之后,我的主要部分似乎是从不调用observeSingleEvent的内部,因此数组没有被填充。任何帮助表示赞赏!

编辑:所以现在正在调用observeSingleEvent,并正确填充myArray,但是当在observeSingleEvent之外的任何地方调用myArray时,数组表明它是空的,即使在observeSingleEvent中,它也是正确填充的。

1 个答案:

答案 0 :(得分:0)

这不是您正在寻找的正确方法,

observeSingleEvent是异步方法,因此在从Firebase服务器执行并获取数据之前,您不会获得输出。

因此,处理此异步任务的最佳方法有两种,
1。)当应用程序从AppDelegate启动并在ViewController中使用时加载这些数据,
2。)或显示加载指示符,直到从服务器获取数据,并从observeSingleEvent内部处理。