2017-08-05 99 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

相關問題