使用firebase数据填充集合视图

Mar*_*ark 7 ios firebase swift firebase-realtime-database firebase-storage

我正在尝试重新创建一个新的firebase项目,其中使用来自firebase实时数据库的数据填充表视图,该数据包含指向firebase存储中图像的链接.

我可以填充教程项目,该项目是带有firebase数据的表视图.但是对于我当前的项目,它是扩展中的集合视图.

我已经把问题缩小到我的变量

  var ref: FIRDatabaseReference!
  var messages: [FIRDataSnapshot]! = []
  var msglength: NSNumber = 10
  private var _refHandle: FIRDatabaseHandle!
Run Code Online (Sandbox Code Playgroud)

特别

var messages: [FIRDataSnapshot]! = []
Run Code Online (Sandbox Code Playgroud)

我认为这是我从firebase获得的数据数组

然后我调用一个函数,该函数应该在我的viewdidload()中填充该数组

func loadPosts(){
    self.messages.removeAll()
    // Listen for new messages in the Firebase database
    _refHandle = self.ref.child("messages").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
        //print("1")
        self.messages.append(snapshot)
        //print(self.messages.count)
    })
}
Run Code Online (Sandbox Code Playgroud)

当我尝试填充我的集合视图时会出现问题,因为我想要水平滚动我使用扩展名.在扩展中,我发现我的值数组总是0,但在我的loadPosts()函数中,my>数组的计数值与我在firebase中的帖子数量相同.

extension HomeViewController : UICollectionViewDataSource
{

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return messages.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    print(messages.count)

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StoryBoard.CellIdentifier, forIndexPath: indexPath) as! InterestCollectionViewCell

    // Unpack message from Firebase DataSnapshot
    let messageSnapshot: FIRDataSnapshot! = self.messages[indexPath.row]
    let message = messageSnapshot.value as! Dictionary<String, String>
    let name = message[Constants.MessageFields.name] as String!
    if let imageUrl = message[Constants.MessageFields.imageUrl] {
        if imageUrl.hasPrefix("gs://") {
            FIRStorage.storage().referenceForURL(imageUrl).dataWithMaxSize(INT64_MAX){ (data, error) in
                if let error = error {
                    print("Error downloading: \(error)")
                    return
                }
                cell.featuredImageView?.image = UIImage.init(data: data!)
            }
        } else if let url = NSURL(string:imageUrl), data = NSData(contentsOfURL: url) {
            cell.featuredImageView?.image = UIImage.init(data: data)
        }
        cell.interestTitleLabel?.text = "sent by: \(name)"
    }
        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该不使用FIRDataSnapshot吗?如果是这样,哪个是正确的?或者我应该以不使用扩展的另一种形式来处理项目?

Mac*_*ath 7

您正确地在完成块中将项目插入到数组中,但是您缺少重新加载collectionView的调用.