目前仍在尝试使用 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内部它已正确填充。
最佳答案
这不是您正在寻找的正确方法,
observeSingleEvent
是异步方法,因此在执行该方法并从 Firebase 服务器获取数据之前,您不会获得输出。
因此处理此异步任务的最佳方法有两种,
1.) 当应用程序从 AppDelegate 启动时加载这些数据并在 ViewController 中使用,
2.) 或显示加载指示器,直到从服务器获取数据,并从 observeSingleEvent
内部处理它。
关于arrays - 使用 Firebase 填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173526/