Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve all values from a sub child in Firebase with Swift iOS

I am trying to retrieve all the values from sub-child of Firebase to show in a label in the collection view. I have to get connections outlets to a Collection View Cell and have a View controller having an image and three labels. In the last label, I want to get all the price value from firebase child.

Firebase Structure

enter image description here

ViewController

enter image description here

Retrieving values

  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.
}

}

latest error

enter image description here

Another Way same class

 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.
}

}

Another Ways Error
enter image description here

like image 303
Xcodian Solangi Avatar asked Feb 23 '17 12:02

Xcodian Solangi


2 Answers

you are getting below error as the value is not array of dictionary, value there is string.

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

it should be

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

Don't see use of fruitArray after assign cake rate in fruitArray

I would suggest you to fill cakeArray as below code:

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()

Second error: I don't see any object as key in cake struct. So compiler is give error. You are assigning value in previous line for cakeRateLabs. So no need to assign again just remove/comment cell.cakeRateLabs.text = cakeArray[indexPath.item].key.

Hope This will surely solve your error and get output as your want.

like image 168
sschunara Avatar answered Oct 25 '22 02:10

sschunara


I wrote a new class and new fetch func. See how this works for you,

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
       }
     }

Fetch Function,

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
   })
}

here it is according to your code,

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 
    }


}
like image 31
K-2SO Avatar answered Oct 25 '22 01:10

K-2SO