arrays - tutorial - swift firebase登入




使用Swift iOS從Firebase的子項中檢索所有值 (2)

我正在嘗試從Firebase的子子項中檢索所有值以顯示在集合視圖中的標籤中。 我必須連接到一個集合視圖單元連接,並有一個視圖控制器有一個圖像和三個標籤。 在最後的標籤中,我想要從Firebase子項中獲得所有的價格值。

Firebase結構

視圖控制器

檢索值

  import UIKit
  import  Firebase
 class CakeViewController:  UIViewController , UICollectionViewDelegate,   UICollectionViewDataSource {

@IBOutlet weak var manuCake: UIBarButtonItem!

@IBOutlet weak var cakeCollectionView: UICollectionView!


struct cakeObject {

    var cakeImage : UIImage
    var cakeEnglichName: String
    var cakeUrduName : String
    var cakeRate : String
    var key : String



}

var cakeArray : [cakeObject] = []



override func viewDidLoad() {
    super.viewDidLoad()

    manuCake.target = revealViewController()
    manuCake.action = #selector(SWRevealViewController.revealToggle(_:))
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())



    let ref = FIRDatabase.database().reference().child("Hyderabad").child("Bakery").child("Cake")

    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists() {


            print(snapshot.value as Any)
            let cakeData = snapshot.value as! [String:String]
                for (key,value) in cakeData{
                    //Can set cakeImage and cakeUrduName as per your project
                    cakeArray.append(cakeObject(cakeImage: #imageLiteral(resourceName: "bakery_almond_cake"),cakeEnglinhName: key, cakeUrduName: "آلمنڑ کیک", cakeRate: "\(value)/kg"))
                }
                self.cakeCollectionView.reloadData()
            }

    })



    cakeCollectionView.delegate = self
    cakeCollectionView.dataSource = self

    // Do any additional setup after loading the view.
}





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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CakeCollectionViewCell", for: indexPath)
        as! CakeCollectionViewCell

    cell.cakeImageView.image = cakeArray[indexPath.item].cakeImage
    cell.cakeEngLabs.text = cakeArray[indexPath.item].cakeEnglichName
    cell.cakeUrLabs.text = cakeArray[indexPath.item].cakeUrduName
    cell.cakeRateLabs.text =  cakeArray[indexPath.item].key

    return cell

}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

最新的錯誤

另一種方式相同的類

 import UIKit
 import  Firebase
 class CakeViewController:  UIViewController , UICollectionViewDelegate,   UICollectionViewDataSource {

@IBOutlet weak var manuCake: UIBarButtonItem!

@IBOutlet weak var cakeCollectionView: UICollectionView!


struct cakeObject {

    var cakeImage : UIImage
    var cakeEnglichName: String
    var cakeUrduName : String
    //var cakeRate : String
    var key : String



}

var cakeArray : [cakeObject] = []



override func viewDidLoad() {
    super.viewDidLoad()

    manuCake.target = revealViewController()
    manuCake.action = #selector(SWRevealViewController.revealToggle(_:))
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())



    let ref = FIRDatabase.database().reference().child("Hyderabad").child("Bakery").child("Cake").child("Almond_Cake")

    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists() {


            print(snapshot.value as Any)
             let cakeData = snapshot.value as! [String:String]
                for (key,value) in cakeData{
                    //Can set cakeImage and cakeUrduName as per your project
                    self.cakeArray.append(cakeObject(cakeImage: #imageLiteral(resourceName: "bakery_almond_cake"),cakeEnglichName: key, cakeUrduName: "آلمنڑ کیک", key: "\(value)/kg"))
                }
                self.cakeCollectionView.reloadData()
            }
       })



    cakeCollectionView.delegate = self
    cakeCollectionView.dataSource = self

    // Do any additional setup after loading the view.
}





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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CakeCollectionViewCell", for: indexPath)
        as! CakeCollectionViewCell

    cell.cakeImageView.image = cakeArray[indexPath.item].cakeImage
    cell.cakeEngLabs.text = cakeArray[indexPath.item].cakeEnglichName
    cell.cakeUrLabs.text = cakeArray[indexPath.item].cakeUrduName
    cell.cakeRateLabs.text =  cakeArray[indexPath.item].key

    return cell

}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

另一種方式錯誤


你正在獲取下面的錯誤,因為值不是字典數組,值是字符串。

if let cake = snapshot.value![a] as? [[String:String]]

它應該是

if let cake = snapshot.value![a] as? String

fruitArray中分配蛋糕速度後,沒有看到fruitArray的使用

我建議你填寫cakeArray如下代碼:

print(snapshot.value as Any)
let cakeData = snapshot.value as! [String:String]
    for (key,value) in cakeData{
           //Can set cakeImage and cakeUrduName as per your project
           cakeArray.append(cakeObject(cakeImage: #imageLiteral(resourceName: "bakery_almond_cake"),cakeEnglinhName: key, cakeUrduName: "آلمنڑ کیک", cakeRate: "\(value)/kg"))                  
      }
    self.cakeCollectionView.reloadData()

第二個錯誤 :我沒有看到任何對像作為蛋糕結構中的鍵。 所以編譯器是給錯誤的。 您正在為cakeRateLabs前一行分配值。 所以不需要再次指定remove / comment cell.cakeRateLabs.text = cakeArray[indexPath.item].key

希望這肯定會解決你的錯誤,並得到你想要的輸出。


我寫了一個新的類和新的獲取函數。 看看這對你如何工作,

class CakeData {
   var cakeImage : UIImage?
   var cakeEnglichName: String?
   var cakeUrduName : String?
   //var cakeRate : String
    var key : String?
 init(postKey: String, postData: Dictionary <String, Any>) {
       self.key = postKey

       //Don't forget to add your keys
       if let cakeImage   = postData["addKey"] {
          self.cakeImage = cakeImage as? UIImage
       }
       if let cakeEnglichName = postData["addKey"] {
          self.cakeEnglichName = cakeEnglichName as? String
       }
       if let cakeUrduName = postData["addKey"] {
          self.cakeUrduName = cakeUrduName as? String
       }
     }

取函數,

func fetchCakeData() {
    let ref = FIRDatabase.database().reference()
ref.child("Hyderabad").child("Bakery").child("Cake").observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
       if let cakeSnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
           for cakes in cakeSnapshot {
               if let cakeDictionary = cakes.value as? Dictionary <String, Any> {
                   let key = cakes.key as String
                   //your class that takes a key as String and a Dictionary
                   let post = CakeData(postKey:key, postData: cakeDictionary)
                   self.cakeArray.append(post)
               }
           }
       }
      cakeCollectionView.delegate = self
     cakeCollectionView.dataSource = self
   })
}

這裡是根據你的代碼,

import UIKit
import Firebase

struct cakeObject {
    var cakeImage : UIImage
    var cakeEnglichName: String
    var cakeUrduName : String
    // var cakeRate : String
    var key : String
}
class CakeData {
    var cakeImage : UIImage?
    var cakeEnglichName: String?
    var cakeUrduName : String?
    //var cakeRate : String
    var key : String?
    init(postKey: String, postData: Dictionary <String, Any>) {
        self.key = postKey

        //Don't forget to add your keys
        if let cakeImage   = postData["addKey"] {
            self.cakeImage = cakeImage as? UIImage
        }
        if let cakeEnglichName = postData["addKey"] {
            self.cakeEnglichName = cakeEnglichName as? String
        }
        if let cakeUrduName = postData["addKey"] {
            self.cakeUrduName = cakeUrduName as? String
        }
    }
}


class CakeViewController: UIViewController , UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var manuCake: UIBarButtonItem!
    @IBOutlet weak var cakeCollectionView: UICollectionView!
    var cakeArray: [CakeData] = []
// var cakeArray : [cakeObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        manuCake.target = revealViewController()
        manuCake.action = #selector(SWRevealViewController.revealToggle(_:))
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        self.cakeCollectionView.delegate = self
        self.cakeCollectionView.dataSource = self
    }

    override func viewWillAppear(_ animated: Bool) {
        fetchCakeData()
    }

    func fetchCakeData() {
        let ref = FIRDatabase.database().reference()
        ref.child("Hyderabad").child("Bakery").child("Cake").observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
            if let cakeSnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for cakes in cakeSnapshot {
                    if let cakeDictionary = cakes.value as? Dictionary <String, Any> {
                        let key = cakes.key as String
                        //your class that takes a key as String and a Dictionary
                        let post = CakeData(postKey:key, postData: cakeDictionary)
                        self.cakeArray.append(post)
                    }
                }
            }
            self.cakeCollectionView.reloadData()
        })
    }




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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CakeCollectionViewCell", for: indexPath)
            as! CakeCollectionViewCell

        cell.cakeImageView.image = cakeArray[indexPath.item].cakeImage
        cell.cakeEngLabs.text = cakeArray[indexPath.item].cakeEnglichName
        cell.cakeUrLabs.text = cakeArray[indexPath.item].cakeUrduName
        cell.cakeRateLabs.text = cakeArray[indexPath.item].key



        print("Cake : \(cakeArray[indexPath.row])")
        cell.cakeImageView.image = cakeArray[indexPath.item].cakeImage
        cell.cakeEngLabs.text = cakeArray[indexPath.item].cakeEnglichName


        return cell 
    }


}




uicollectionview