8

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

我可以填充教程项目,它是一个带有 firebase 数据的表格视图。但是对于我当前的项目,它是扩展内的集合视图。

我已将问题缩小到我的变量

  var ref: FIRDatabaseReference!
  var messages: [FIRDataSnapshot]! = []
  var msglength: NSNumber = 10
  private var _refHandle: FIRDatabaseHandle!

具体来说

var messages: [FIRDataSnapshot]! = []

我认为这是我从 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)
    })
}

当我尝试填充我的集合视图时会发生此问题,因为我想要水平滚动我使用扩展。在扩展中,我发现我的值数组始终为 0,但在我的 loadPosts() 函数中,我的 >array 的计数与我在 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
    }
}

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

4

1 回答 1

8

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

于 2016-05-20T10:32:21.040 回答