How to push the Selection of a UIPicker to Firebase - swift

how can I push the User Selection of a UIPicker to Firebase Database? So for example he hit on "male" than it will be stored in the Firebase Database...
My code for the UI Picker
class AddExtraData: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return data[row]
}
#IBOutlet var pickerView: UIPickerView!
let data = ["male", "female", "else"]
override func viewDidLoad() {
super.viewDidLoad()
pickerView.dataSource = self
pickerView.delegate = self
}
EDIT:
Database
Here is my database.
Now I want to get to write the data which is stored in seclectedYearPicker to the database.
var ref: DatabaseReference!
ref = Database.database().reference()
let selectedYearPicker = data[pickerView.selectedRow(inComponent: 0)]
print(selectedYearPicker)
let userID = Auth.auth().currentUser!.uid
ref.child("users").child(userID).setValue(["gender": selectedYearPicker])
}
If I make this, there will be a new dataset:
let db = Firestore.firestore()
db.collection("users").whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "x")
.getDocuments { (querySnapshot, err) in
if err != nil {
print("Failed")
return
}
let userdocid = querySnapshot!.documents[0].documentID
db.collection("users").document(userdocid).setData(["koordinaten" : selectedYearPicker])
}

Related

How to sort AVSpeechSynthesisVoice.speechVoices()

I'm a beginner, and I'm while working on this, I noticed that the picker view isn't sorted
Obviously Chinese does not come after Turkish, so how do I sort it up? I've been looking at my code for hours and can't seem to figure out how to get it sorted. Here's my complete code.
Thanks
import AVFoundation
import UIKit
class SettingsView: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var pickerView: UIPickerView!
var voicesArray: [String] = []
let speechVoices = AVSpeechSynthesisVoice.speechVoices()
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return speechVoices.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let language = Locale.current.localizedString(forLanguageCode: speechVoices[row].language)!
let languageCode = speechVoices[row].language
var regionCode:String = ""
for region in Locale.isoRegionCodes {
// Test if provided region codes has voices or not
if languageCode.contains(region) {
regionCode = region
}
}
let country = Locale.current.localizedString(forRegionCode: String(regionCode))
return "\(language) (\(country ?? ""))"
}
#IBAction func done(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
Chinese (zh) definitely comes after Turkey (tr), so these appear already sorted by region code. If you want to sort by something else (I assume their display name in the locale language), then you can sort them when you set up your list of elements for the picker. For example:
let speechVoices = AVSpeechSynthesisVoice.speechVoices().sorted(by: {
Locale.current.localizedString(forLanguageCode: $0.language)! < Locale.current.localizedString(forLanguageCode: $1.language)!
})

REALM Append list into linkingObjects

I want to use realm to append all data in one VC.
parentVC is showing Category List, in ParentVC can only append new Category
childVC is showing toDoItem List, and can only append to selectedCategory.toDoList
I created a new VC "addToDoListVC", to achieve result of "Adding new toDoItems to selected todoListCategory".
below is my code and image shown is the new addToDoListVC layout.
addToDoItemVC layout
class Category : Object {
#objc dynamic var categoryName : String = ""
let ofToDoItem = List<ToDoItem>()
}
class ToDoList : Object {
#objc dynamic var toDoItem : String = ""
var parentCategory = LinkingObjects(fromType: Category.self, property: "ofToDoItem")
}
addItemVC
let realm = try! Realm()
var categorySelection : Results<Category>?
#IBOutlet weak var categoryName: UILabel!
#IBOutlet weak var categoryNamePicker: UIPickerView!
#IBAction func addItemBtnPressed(_ sender: UIButton) {
if let currentCategory = self.categorySelection {
do {
try! realm.write
let newToDoItem = ToDoList()
**// HOW DO I ADD THE ITEM TO SELECTED CATEGORY?**
newToDoItem.toDoItem = textField.text
selectedCategory[**???**].ofToDoItem.append(newToDoItem)
**[// I can append data into selected category by "selectedCategory\[0\].ofToDoItem.append(newToDoItem)" but it is hardcoded.][1]**
}
}
}
//MARK:- PICKERVIEW METHODS
extension ParentVC : UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return categorySelection?.count ?? 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return categorySelection?[row].categoryName
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
categoryName.text = categorySelection?[row].categoryName
}

Display Firebase data inside PickerView

CODE HAS BEEN UPDATED AND IS WORKING AS EXPECTED
I have a View Controller with a text field and a PickerView. I want to display the data i have stored in Firebase inside the PickerView. I'm able to retrieve and print the data from Firebase but I can't find a way to display it inside the PickerView. Here is my code:
import UIKit
import Firebase
class pickerVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var labelTxt: UITextField!
#IBOutlet weak var infoPickerViewer: UIPickerView!
var dbRef: CollectionReference!
var pickerView: UIPickerView?
var itemsClass = [ItemInfo]()
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
infoPickerViewer.delegate = self
infoPickerViewer.dataSource = self
dbRef = Firestore.firestore().collection(ITEMS_REF)
labelTxt.inputView = pickerView
labelTxt.delegate = self
self.infoPickerViewer = pickerView
self.infoPickerViewer?.delegate = self
self.infoPickerViewer?.dataSource = self
self.infoPickerViewer.reloadAllComponents()
getItems()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func textFieldDidBeginEditing(_ textField: UITextField) {
labelTxt = textField
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.pickerView?.reloadAllComponents()
return true
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if labelTxt.isFirstResponder {
return self.itemsClass.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if labelTxt.isFirstResponder {
return itemsClass[row].itemName
}
return nil
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if labelTxt.isFirstResponder {
let item = itemsClass[row].itemName
labelTxt.text = item
}
}
func getItems() {
dbRef.getDocuments { (snapshot, error) in
if let err = error {
debugPrint("error fetching docs: \(err)")
} else {
self.infoPickerViewer.reloadAllComponents()
let snap = snapshot
for document in snap!.documents {
let data = document.data()
let itemCode = data[ITEMS_CODE] as? String ?? ""
let itemName = data[ITEMS_NAME] as? String ?? ""
let t = ItemInfo(itemCode: itemCode, itemName: itemName)
self.itemsClass.append(t)
print("ITEMS_CODE", itemCode as Any)
print("ITEMS_NAME", itemName as Any)
}
}
}
}
}
The Firebase DB is structured as follow:
collection/AutoID/itemCode: "item1"
itemName: "item2"
collection/AutoID/itemCode: "item3"
itemName: "item4"
I only need to display the itemName inside the PickerView, the itemCode I'm going to use it to run a query depending on the selection in the PickerView.
Any help with this is greatly appreciated.

How to get the value that the user chose from a UIPickerView?

This is what I'm trying to accomplish:
I want to take the value that the user selected from 2 different pickerViews and display that value in a textField
let drivingGear = ["1", "12", "36", "60", "84"]
let boxVal = chooseDrivingGear
let boxVal2 = chooseDrivenGear1
let newVal = boxVal / boxVal2
resultBox1.text = newVal
However I couldnt get that to work so I'm now trying this:
#IBAction func chooseBox1Pressed(_sender: UIButton) {
sender.isHidden = true
if chooseDrivingGear.isHidden {
chooseDrivingGear.isHidden = false
}
if chooseDrivingGear[row] == "1" {
let v1 = 1
}
but chooseDrivingGear[row] shows this error: use of unresolved identifier 'row'
(My other code for pickerview) UPDATE:
//first picker view
chooseDrivingGear.isHidden = true
chooseDrivingGear.delegate = self
chooseDrivingGear.dataSource = self
chooseDrivingGear.tag = 0
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 0 {
chooseBox1.setTitle(drivingGear[row], for: .normal)
chooseDrivingGear.isHidden = true
chooseBox1.isHidden = false
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return drivingGear[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return drivingGear.count
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
chooseDrivingGear.isHidden = false
chooseDrivingGear2.isHidden = false
chooseDrivingGear3.isHidden = false
chooseDrivenGear1.isHidden = false
chooseDrivenGear2.isHidden = false
chooseDrivenGear3.isHidden = false
return false
}
You can simply try getting the selectedRow from both the pickerViews, get the values for the selected rows and the perform calculation on the values as required to show in the textField.
I have provided a sample code for that below.
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
{
#IBOutlet weak var pickerView1: UIPickerView!
#IBOutlet weak var pickerView2: UIPickerView!
#IBOutlet weak var textField: UITextField!
let drivingGear = ["1", "12", "36", "60", "84"]
override func viewDidLoad()
{
super.viewDidLoad()
}
#IBAction func showResult(_ sender: UIButton)
{
let val1 = self.drivingGear[self.pickerView1.selectedRow(inComponent: 0)]
let val2 = self.drivingGear[self.pickerView2.selectedRow(inComponent: 0)]
if let intVal1 = Int(val1), let intVal2 = Int(val2)
{
let result = intVal1 / intVal2
self.textField.text = String(result)
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return self.drivingGear.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return self.drivingGear[row]
}
}
Let me know if you still face any issues.

Can't get app to display cryptocurrency amount

From "var myValue:[Double]..." and "var activeCurrency:Double = 0;" to the third pickerview code, I am not sure what to do in order to fix the "self.myValues.append((Url as? Double)!)" so that my app displays the currency amount. I have searched everywhere, and have no luck in finding anything. You are my last hope, please help. I'm still fairly new to coding, so I may not know the certain jargon.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var myCurrency:[String] = []
var myValues:[Double] = []
var activeCurrency:Double = 0;
//OBJECTS
#IBOutlet weak var textbox: UITextField!
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var output: UILabel!
//CREATING PICKER VIEW
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return myCurrency.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return myCurrency[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
activeCurrency = myValues[row]
}
//BUTTON
#IBAction func action(_ sender: AnyObject) {
if (textbox.text != "") {
output.text = String(Double(textbox.text!)! * activeCurrency)
}
}
override func viewDidLoad() {
super.viewDidLoad()
//DATA GRABBING
let url = URL(string: "https://min-api.cryptocompare.com/data/all/coinlist")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print ("ERROR")
}
else {
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let rates = myJson["Data"] as? NSDictionary {
for (Name, Url) in rates {
self.myCurrency.append((Name as? String)!)
self.myValues.append((Url as? Double)!)
}
}
}
catch {
}
}
}
if data != nil {
DispatchQueue.main.async { // Correct
self.pickerView.reloadAllComponents()
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}