Search code examples
iosswiftfirebaseuipickerview

Attempting to send data from a UIPicker to Firebase Database


So I have figured out how to send textfield data in to the database whilst giving each customer's order a unique key, in the next view or next screen, I need to limit what selections a customer makes so I have placed instead of a text field a UIPicker with various options. I need the option that the customer selects to also appear in my database under the same key as the one used in the previous screen.

class flavorViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    var customerInfo: FIRDatabaseReference!
    @IBOutlet weak var flavorPicker: UIPickerView!

    var flavors: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        FIRApp.configure()
        customerInfo = FIRDatabase.database().reference().child("Customer Info");

        self.flavorPicker.dataSource = self
        self.flavorPicker.delegate = self

        //List Picker Data Here
        flavors = ["Double Apple", "Watermelon Mint", "Blueberry Mint", "Grape Mint", "Geisha", "Sex on the Beach"]
    }

    // The number of columns of data
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    // The number of rows of data
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return flavors.count
    }

    // The data to return for the row and component (column) that's being passed in
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return flavors[row]
    }

    func flavorselected() {
        let key = customerInfo.childByAutoId().key

        let flavor = ["id": key,"flavor selected": flavorPicker.selectedRow as Int ]
    }

    @IBAction func checkoutButton(_ sender: Any) {
        flavorselected()
    }

Here is all the code I have for setting everything up however, I get an error:

Cannot convert value of type '(Int) -> Int' to type 'Int' in coercion

Furthermore, while I haven't attempted this yet, will this selection be merged with the data the user has entered in the previous screen to the database? Or will it create a separate entry.


Solution

  • Your issue is on this line:

    let flavor = ["id": key,"flavor selected": flavorPicker.selectedRow as Int ]
    

    and it is caused by:

    flavorPicker.selectedRow as Int
    

    selectedRow is a function that takes and Int parameter. You need to change this to:

    let flavor: [String: Any] = ["id": key,"flavor selected": flavorPicker.selectedRow(inComponent: 0) ]