Home How to load data retrieved from Firebase in UIPickerView?
Reply: 0

How to load data retrieved from Firebase in UIPickerView?

user4541
1#
user4541 Published in July 23, 2018, 3:53 am

I populate a UIPickerView with data from bookingInfo and it works as expected. However, I need to add one more row in the UIPickerView and assign it a "default value". In order to do this in numberOfRowsInComponent I return bookingInfo.count + 1 The problem is that I get error index out of range in the switch statement. I am not sure if it is because firebase retrieves the data asynchronously.

class ContactUs: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

var currentUid:String!
var dbRef:FIRDatabaseReference! 
var bookingInfo = [FireBaseData]() // this array will hold all bookings for the logged in user
@IBOutlet weak var bookingsPickerView: UIPickerView!

 override func viewDidLoad() {
    super.viewDidLoad()

    bookingsPickerView.delegate = self
    bookingsPickerView.dataSource = self

    guard let uid = FIRAuth.auth()?.currentUser?.uid else {
        return
  }
    self.currentUid = uid
    dbRef = FIRDatabase.database().reference().child("Cleaners")
    startObservingDB() // observe the database for value changes
}//end of viewDidLoad


   func numberOfComponents(in pickerView: UIPickerView) -> Int {
       return 1
  }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return bookingInfo.count + 1 //if I don't add 1 my code will run properly
 }

 func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37)))

    if bookingInfo.isEmpty == false {

        switch row{
         case 0...bookingInfo.count:
            //Prints index out of range
            let booking = self.bookingInfo[row]
            label.text = String(booking.BookingNumber) + " " + String(booking.DateAndTime)

        default:
            label.text = "default Value"
        }   
     }
     return label
   }
}// end of class ContactUs



extension ContactUs {

//observe firebase at a specific reference for values changes
func startObservingDB() {

    dbRef.child(currentUid).child("bookings").observe(.value, with: { (snapshot: FIRDataSnapshot) in

        //instance of FireBaseData holding all bookings under currentUid
        var newBookingInfo = [FireBaseData]()


            //iterate over each booking which is located under 'bookings'
            for booking in snapshot.children {
                var bookingItem = FireBaseData(snapshot: booking as! FIRDataSnapshot)
                newBookingInfo.append(bookingItem) 
            } 

        //assign newBookingInfo to global variable
        self.bookingInfo = newBookingInfo

   //sort the array in place so that the most recent date will appear first
        self.bookingInfo.sort(by: {(DateAndTimeObject_1,DateAndTimeObject_2) -> Bool in  
            DateAndTimeObject_1.TimeStampDateAndTime > DateAndTimeObject_2.TimeStampDateAndTime
        })

        // after Firebase retrieves all bookings, reload the componets in the picker view so that the methods belonging to protocol UIPickerViewDelegate will be called
        self.bookingsPickerView.reloadAllComponents()
    }, withCancel: { (Error:Any) in
        print("Error firebase \(Error)")
    })  
 } // end of startObservingDB()

}//end of extension

Update

Thanks to @livtay my code works. How can I have "Other" value show on the first row when bookingInfo array is not empty rather than on the last row as it shows now?
My progress so far.

   func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37)))
        label.textAlignment = .left     

    if bookingInfo.isEmpty == true {
         label.text = "Other"
         self.pickerViewTitle = "Other"

        } else {

        switch row{
          case 0...bookingInfo.count - 1:
              let booking = self.bookingInfo[row]
              self.pickerViewTitle = String(booking.BookingNumber) + " " + String(booking.DateAndTime)
              label.text = self.pickerViewTitle

        default:
            label.text = "Other"
             self.pickerViewTitle = "Other"
        }
    }
    return label 
}

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309352 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO