使用Firebase数据填充集合视图 [英] Populate a collection view with firebase data

查看:107
本文介绍了使用Firebase数据填充集合视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试重新创建一个新的Firebase项目,在其中填充表格视图,其中包含来自Firebase实时数据库的数据,其中包含指向Firebase存储中图片的链接。

我可以使用firebase数据填充教程项目,该项目是一个表视图。但与我目前的项目,它是一个扩展内的集合视图。



我已经将问题缩小到了我的变量中。

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

特定

  var消息:[FIRDataSnapshot]! = [] 

我认为这是我从Firebase获得的数据的一个数组。 b
$ b

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

  func loadPosts(){
self.messages.removeAll()
//在Firebase数据库中侦听新消息
_refHandle = self.ref.child(messages)。observeEventType(.ChildAdded ,withBlock:{(snapshot) - >无效
// print(1)
self.messages.append(快照)
//print(self.messages.count)
})
}




当我尝试填充我的集合视图,因为我想水平滚动我使用扩展。在扩展中,我发现我的数组数组始终是0,但在我的loadPosts()函数中,my>数组的计数与我在firebase中发布的数量相同。




 扩展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

//从Firebase DataSnapshot解包消息
let messageSnapshot:FIRDataSnapshot! = self.messages [indexPath.row]
let message = messageSnapshot.value as! Dictionary< String,String>
让name = message [Constants.MessageFields.name]作为字符串!
if imageUrl = message [Constants.MessageFields.imageUrl] {
if imageUrl.hasPrefix(gs://){
FIRStorage.storage()。referenceForURL(imageUrl).dataWithMaxSize (错误下载:\(错误))
返回
} $ b $($ INT $ _ $ MAX $) b cell.featuredImageView?.image = UIImage.init(data:data!)
}
} else if url = NSURL(string:imageUrl),data = NSData(contentsOfURL:url){
cell.featuredImageView?.image = UIImage.init(data:data)
}
cell.interestTitleLabel?.text =sent by:\(name)
}
返回单元格
}
}

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

解决方案

块,但你缺少一个调用来重新加载你的collectionView。

I'm trying to recreate a new firebase project where you populate a table view with data from firebase realtime database that contain links to images in firebase storage.

I can populate the tutorial project which is a table view with firebase data. But with my current project it is a collection view inside an extension.

I've narrowed down the issue to my variables

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

specifically

var messages: [FIRDataSnapshot]! = []

Which I think is an array of my data I get from firebase

I then call a function that should populate that array in my 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)
    })
}

The issue happens when I try to populate my collections view since I want horizontal scrolling I use an extension. In the extension I find that my array of values is always 0, but in my loadPosts() function the count of my >array is the same value as the amount of posts I have in 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
    }
}

Should I not be using FIRDataSnapshot? If so which is the correct one to use? Or should I approach the project in another form not using extensions?

解决方案

You are correctly inserting the items into your array within the completion block, but you are missing a call to reload your collectionView.

这篇关于使用Firebase数据填充集合视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆