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 を使用すべきではありませんか? もしそうなら、どれを使うのが正しいですか?それとも、拡張機能を使用しない別の形でプロジェクトにアプローチする必要がありますか?