Lets say you are using SwiftyJson from json parsing and Alamofire for hiting API.
when you hit API you can make a model using swiftyjson for example
import Foundation
import SwiftyJSON
struct UnitsModel {
var id: Int = 0
var name: String = ""
init(fromJson Json: JSON!) {
if Json.isEmpty {
return
}
id = Json["id"].intValue
name = Json["name"].stringValue
}}
Now you need to map json response to your array and to do that you can use
fileprivate func APIRequestGetUnitsCompleted(response: Any?, error: Error?) {
if let response = response{
let json = JSON(response)
let units = json["units"].arrayValue
for index in 0..<units.count{
let model = UnitsModel(fromJson: units[index])
unitsArray.append(model)
}
}else{
//print("Error")
}
}
In your view controller make an array of type model which you just created and also create a variable to store ID
var unitsArray = [UnitsModel]()
var selectedUnitId = 0
Now you can use following code:
ViewController: UIPickerViewDelegate, UIPickerViewDataSource{
func createPickerView() {
pickerView.delegate = self
unitTextField.inputView = pickerView
}
func dismissPickerView() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let button = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.action))
toolBar.setItems([button], animated: true)
toolBar.isUserInteractionEnabled = true
unitTextField.inputAccessoryView = toolBar
}
@objc func action() {
view.endEditing(true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return unitsArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return unitsArray[row].name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
unitTextField.text = unitsArray[row].name
selectedUnitId = unitsArray[row].id
// selectedUnitId is variable in which id of selected option from picker view will be saved.
}}