2017-04-08 112 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)

相關問題