2017-08-05 100 views
1

嗨我想获得在Firebase数据库中的numOfVids,所以我可以在我的numberOfItemsInSection中返回该数字。但它返回0而不是6.我知道它返回0,因为它读取的是空变量,而不是observeSingleEvent中的变量。如何在swift 3中得到这个变量的编号?

有什么办法让我获得修改的numOfVids而不是 空的numOfVids?

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    var numOfVids = Int() // 0 
    let videosRef = FIRDatabase.database().reference().child("users/\(currentUserID)/videos") 

    videosRef.observeSingleEvent(of: .value, with: { (snapshot) in 
     //get user value 
     numOfVids = Int(snapshot.childrenCount) 
     print(numOfVids) //prints 6 

    }) 

    return numOfVids //returns 0 
} 

预先感谢您!

+9

**永远不要**把一个异步任务放在一个方法里面应该返回一些东西。它不会工作。找到另一个解例如,使用数据源模型,在'viewWillAppear'中加载数据,并在观察方法的完成处理程序中重新加载集合视图。 – vadian

+0

确切地说,在UICollectionViewDataSource的方法中做这个工作是不好的方法。 – Malder

回答

0

尝试: -

var numOfVids : Int = 0 
@IBOutlet weak var my_CollectionView: UICollectionView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.my_CollectionView.delegate = self 
    self.my_CollectionView.dataSource = self 

    loadData { (check) in 
     print(check) 
    } 

} 


override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

    // Use only when you want to reload your data every time your view is presented. 
     /* 
    loadData { (check) in 
     print(check) 
    } 
    */ 
} 

func loadData(completionBlock : @escaping ((_ success : Bool?) -> Void)){ 

    Database.database().reference().child("your_PATH").observeSingleEvent(of: .value, with: {(Snap) in 

     // Once you have retrieved your data 
     // Update the count on the class local variable -- numOfVids 
     // Reload your collectionView as .. 

     self.my_CollectionView.reloadData() 
     completionBlock(true) 

    }) 

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

    return numOfVids 

    } 
+0

hmhm,我试过了,但是它返回0 –

+1

@ErikBatista你将不得不在loadData处理程序中更新你的'numOfVids' ... – Dravidian

-4

试试这个:

let videosRef = FIRDatabase.database().reference().child("users/\(currentUserID)/videos") 

    videosRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in 
     for data in snapshot.children.allObjects as! [DataSnapshot] { 
      if let data = data.value { 

       self.numOfVids = self.numOfVids + 1 

      } 
     } 
     print(numOfVids) 
    }) 

和关于变量numOfVids:

var numOfVids = 0 

这应该工作的感谢

+0

它与我一起工作,我正在使用它并在视图之间传递值.. .etc – ushehri

+0

这绝对是**不**工作'numberOfItemsInSection' – vadian

+0

我错过了什么在这里?你的意思是代码不起作用或者不能解决问题? – ushehri

相关问题