2017-04-08 53 views
1

我试图从Firebase(数据库+存储)下载一些信息,然后填充集合视图。但我无法对从Storage下载的数据进行排序!(Swift)如何对从Firebase Storage下载的数据进行排序?

我的数据库结构如下:

所有的
{ 
    "Cards": { 
    "id_0": { 
     "title": "0", 
     "timestamp": "-0000105", 
     "photoURL": "http:// ..." 
    }, 
    "id_1": { 
     "title": "1", 
     "timestamp": "-0000102", 
     "photoURL": "http:// ..." 
    }, 
    "id_2": { 
     "title": "2", 
     "timestamp": "-0000100", 
     "photoURL": "http:// ..." 
    }, 

    (...) // Up to 15 
    } 
} 

首先,我开始下载从火力地堡的数据库信息。然后,我抓取这些项目中的每一个的“photoURL”数据,然后从Firebase存储中继续下载其通信照片。

为了获取按日期排序的数据,我使用queryOrdered by“timestamp”。它工作正常:它收到id_0,然后id_1,然后id_2等。

然而,当我开始下载从存储的照片,我的“标题”信息不符合,我下载的照片:

Example - How it is

Example - How I want it to be

所以,我只是希望每个照片弹出集合视图中的正确位置。

有没有人知道最好的办法呢?谢谢!

这里是我的代码:

注:我不喜欢使用辅助变量“countCalls”和“secondaryCountCalls”这种做法。

import Foundation 
import UIKit 
import Firebase 
import FirebaseStorage 
import FirebaseDatabase 
import FirebaseAuth 

var currentCollectionViewData = [UIImage]() 

struct item { 
    let photoURL : String! 
    let title : String! 
    let timestamp : Int! 
} 

var incomingCards = [item]() 

class HomeView: UIViewController { 

    @IBOutlet weak var collectionView: UICollectionView! 

    override func viewDidLoad() { 

    super.viewDidLoad() 

    // Authorization 
    let uid = FIRAuth.auth()?.currentUser?.uid 

    // Creating reference to database: 
    let databaseRef = FIRDatabase.database().reference() 

    // Getting current date: 
    let currentDate = getCurrentDate() 

    var countCalls = -1 
    var secondaryCountCalls = -1 

    databaseRef.child("CARDS").queryOrdered(byChild: "timestamp").observe(.childAdded, with: { snapshot in 

     var timestamp = (snapshot.value as? NSDictionary)?["timestamp"] as! Int 

     incomingCards.append(item(title: (snapshot.value as? NSDictionary)?[“title”] as! String, 
            photoURL: (snapshot.value as? NSDictionary)?["photoURL"] as! String, 
            timestamp : timestamp)) 

     currentCollectionViewData.append(UIImage(named: "default_Photo")!) 

     self.collectionView!.reloadData() 


     countCalls = countCalls + 1 

     FIRStorage.storage().reference(forURL: incomingCards[countCalls].photoURL).data(withMaxSize: 1 * 1024 * 1024) {(data, error) -> Void in 
      if (error != nil) { 
       print(error) 
      } else { 
       secondaryCountCalls = secondaryCountCalls+1 

       currentCollectionViewData[secondaryCountCalls] = UIImage(data: data!)! 
       self.collectionView!.reloadData() 

      } 
     } 
    }) 

} 

而我扩展的CollectionView:

extension HomeView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{ 
     return CGSize(width: self.collectionView.bounds.width, height: 189) 
    } 



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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

     var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell 

     cell.imageFromCollectionView?.image = currentCollectionViewData[indexPath.row] 

     return cell 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 

     let width = collectionView.frame.width/3 - 1 

     return CGSize(width: width, height: width) 

    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 

     return 0.5 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 

     return 0.5 
    } 
} 

回答

0

我得到了解决!答案是:cellForItemAt和缓存!

首先,刚刚从viewDidLoad中()去掉下面的一段代码:

countCalls = countCalls + 1 

FIRStorage.storage().reference(forURL: incomingCards[countCalls].photoURL).data(withMaxSize: 1 * 1024 * 1024) {(data, error) -> Void in 
if (error != nil) { 
    print(error) 
} else { 
    secondaryCountCalls = secondaryCountCalls+1 
    incomingCards[secondaryCountCalls].photo = UIImage(data: data!)! 
    currentCollectionViewData[secondaryCountCalls] = UIImage(data: data!)! 
    self.collectionView!.reloadData() 
    } 
} 

现在,让我们来创建我们的文件中的以下扩展代码:

extension UIImageView { 

func loadImageUsingCacheWithUrlString(urlString: String) { 

    // check cachae for image first 
    if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage { 
     self.image = cachedImage 
     return 
    } 

    // otherwise fire off a new download 
    let url = NSURL(string: urlString) 

    URLSession.shared.dataTask(with: url! as URL, completionHandler: {(data, response, error) in 

     if error != nil { 
      print(error) 
      return 
     } 

     DispatchQueue.main.sync { 

      if let downloadedImage = UIImage(data: data!) { 

       imageCache.setObject(downloadedImage, forKey: urlString as AnyObject) 
       self.image = downloadedImage 

      } 
     } 
    }).resume() 
} 

最后,里面的cellForItemAt方法,插入以下一段代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell 

    cell.imageFromCollectionView?.loadImageUsingCacheWithUrlString(urlString: incomingCards[indexPath.row].photoURL) 
    currentCollectionViewData[indexPath.row] = cell.imageFromCollectionView.image 

} 

贷记 “让我们建立一个应用程序”,从YouTube(下面的链接)

Swift: Firebase 3 - How to Load Images from Firebase Storage and Caching (Ep 6)

相关问题