Search code examples
xcodefirebasegoogle-cloud-firestoreuiswitch

UISwitch Status to Firestore


I am currently building a user creation mechanism where I have 8 UI switches to determine if someone has a food allergy or not. I have created an @IBOutlet for each switch and now have them contained in the document. I'm having no issue adding text fields:

let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstname, "lastname":lastname, "username":username, ]

What I'd like to do is extend that syntax to add the status of the 8 UISwitch's on user creation.

New to Firebase and app development, but tried Googling everything I could think of. Thanks in advance for your help!

UPDATE OK, so I must still be doing something wrong here, but I think I'm getting close:

import UIKit
import FirebaseAuth
import Firebase

class SignUpViewController: UIViewController {

    @IBOutlet weak var firstNameTextField: UITextField!
    
    @IBOutlet weak var lastNameTextField: UITextField!
    
    @IBOutlet weak var usernameTextField: UITextField!
    
    @IBOutlet weak var emailTextField: UITextField!
    
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var milkSwitch: UISwitch!
    
    @IBOutlet weak var peanutSwitch: UISwitch!
    
    @IBOutlet weak var wheatSwitch: UISwitch!
    
    @IBOutlet weak var treeNutSwitch: UISwitch!
    
    @IBOutlet weak var fishSwitch: UISwitch!
    
    @IBOutlet weak var shellFishSwitch: UISwitch!
    
    @IBOutlet weak var eggSwitch: UISwitch!
    
    @IBOutlet weak var soySwitch: UISwitch!
    
    @IBOutlet weak var addAFamilyButton: UIButton!
    
    @IBOutlet weak var signUpButton: UIButton!
    
    @IBOutlet weak var errorLabel: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setUpElements()
    }
    func setUpElements (){
        errorLabel.alpha = 0
    }
    func showError(_ message:String) {
        errorLabel.text = message
        errorLabel.alpha = 1
    }
    //Check the fields and validate that data is correct.
    func validateFields() -> String? {
    
        //Check that all fields are filled in
        if firstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
            lastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
            usernameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
            emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
            passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
            
            return "Please fill in all fields."
        }
        
        //Check if password is secure
        let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        
        if Utilities.isPasswordValid(cleanedPassword) == false {
      
            // Password isn't secure enough
            return "Please make sure your password is at least 8 characters, contains a special character and a number"
        }
        
        return nil
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func signUpTapped(_ sender: Any) {
        // Validate the fields
        let error = validateFields()
        
        if error != nil {
            // There's something wrong with the fields, show error message
            showError(error!)
        }
        else {
        // Cleaned Versions of the data
            let firstname = firstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
            let lastname = lastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
            let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
            let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
            let username = usernameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
            let milk = milkSwitch
            let peanut = peanutSwitch
            let wheat = wheatSwitch
            let treenut = treeNutSwitch
            let fish = fishSwitch
            let shellfish = shellFishSwitch
            let egg = eggSwitch
            let soy = soySwitch
            
            
        // Create the user
            Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
                // Check for errors
                if err != nil {
                    //There was an error creating the user
                    self.showError("Error creating user")
                }
                else {
                    
                    // User was created successfully
                    let db = Firestore.firestore()
                    db.collection("users").addDocument(data: ["firstname":firstname, "lastname":lastname, "username":username, "uid": result!.user.uid, "milk":milkSwitch.isOn, "peanut":peanutSwitch.isOn, "wheat":wheatSwitch.isOn, "treenut":treeNutSwitch.isOn, "fish":fishSwitch.isOn, "shellfish":shellFishSwitch.isOn, "egg":eggSwitch.isOn, "soy":soySwitch.isOn ]) { (error) in
                        if error != nil {
                            //Show error message
                            self.showError("Your allergies have not been saved. Please login to your account")
                        }
                    }
                    // Transiition to the home screen
                    
                }
            }
        
        
    }
}

Solution

  • You can use isOn to get the status of a UISwitch

    let peanutAllergySwitch = UISwitch()    
    
    let db = Firestore.firestore()
    let data = [
      "firstname":firstname, 
      "lastname":lastname, 
      "username":username, 
      "allergicToPeanuts": peanutAllergySwitch.isOn
    ]
    
    db.collection("users").addDocument(data: data)