Search code examples
iosswiftpicker

How to read and assign data from picker (tried few answers from question and it still unsolved)


So I just wanna to read which option I picked from my picker. I read a few questions and answers but I can't make it work with it. I must doing something wrong. So there is my code:

import UIKit
import Firebase
import FirebaseFirestore

class AddItemViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var itemNameField: UITextField!
    @IBOutlet weak var storeNameField: UITextField!
    @IBOutlet weak var dateOfPurchaseField: UIDatePicker!
    @IBOutlet weak var guaranteePeriodField: UIPickerView!
    let guaranteePeriodData = ["1 Year", "2 Years", "3 Years", "4 Years", "5 Years", "6 Years"]


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        guaranteePeriodField.delegate = self
        guaranteePeriodField.dataSource = self
    }

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return guaranteePeriodData.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return guaranteePeriodData[row]
    }

    @IBAction func addItemButtonTouched(_ sender: Any) {
        let db = Firestore.firestore()

        guard let uid = Auth.auth().currentUser?.uid,
        let name = itemNameField.text else {
                return // return control to the caller or do something else to indicate access denied
        }
        let store = storeNameField.text
        let dateOfPurchase = dateOfPurchaseField.date
        let guaranteePeriod = guaranteePeriodData[guaranteePeriodField.selectedRow(inComponent: print(guaranteePeriod))]
        db.collection("recipes").addDocument(data: ["name": name, "uid": uid, "store": store, "dateOfPurchase": dateOfPurchase, "guaranteePeriod": guaranteePeriod])
        displayAlertMessage(alertTitle: "Success", alertMessage: "New item added successfully.", dismiss: true)
    }

I want to make it simple as possible and I just need to read the value before I save it to firebase.

Edit 1

I getting error:

Unsupported type: UIPickerView (found in field guaranteePeriod)"

This is how I trying to assign value:

let guaranteePeriod = guaranteePeriodField
        db.collection("recipes").addDocument(data: ["name": name, "uid": uid, "guaranteePeriod": guaranteePeriod])

Solution

  • You can read selected value with

    var selectedItem = ""
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            selectedItem = guaranteePeriodData[row]
        }
    

    According to your Update change it like :

    let guaranteePeriod = selectedItem