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
}
}
}
}
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)
Related
I'm trying to go next screen after the save button is pushed, i tried to write code perform segue and i get buch of errors. Below is my code currently, i didn't finish the save part. I wanted to go back to that later time.
I'm new to coding in xcode, so any advice on where to put this code would be nice.
import UIKit
import CoreData
class SignupVC: UIViewController {
#IBOutlet var txtfirstname: UITextField!
#IBOutlet var txtlastname: UITextField!
#IBOutlet var txtUsername: UITextField!
#IBOutlet var txtPassword: UITextField!
#IBOutlet var txtConfirmpassword: UITextField!
#IBOutlet var txtEmail: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signupTapped(_ sender: Any) {
_ = txtUsername.text;
_ = txtPassword.text;
_ = txtConfirmpassword.text;
_ = txtEmail.text;
//check empty fields
if((txtPassword.text?.isEmpty)! || (txtConfirmpassword.text?.isEmpty)! || (txtEmail.text?.isEmpty)!)
{
//Display alert
displayMyAlertMessage(userMessage: "All fields are required")
return;
}
//check if passwords match
if (txtPassword.text != txtConfirmpassword.text)
{
//Display in alert message
displayMyAlertMessage(userMessage: "Passwords don't match");
return;
}
//store Data
// Display alert message with Confirmation
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"ok", style: UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
/*
just go into storyboard and hold control key on the button and let it go on the ViewController you want to go to. Then select the kind. For Example "Show"
then it should work. If you have questions ask.
I have a problem, I want to create a small app in which data in a formula can be charged.
Currently the data from three ViewControllers and one PickerViewController will be given back to the first ViewController.
That works very well too.
Now I want that the data at the start not on "nil" set but have a certain value.
Thereafter, the data entered last should reappear when the app is restarted.
I would like to apologize for my english, it is not my preferred language ...
Here is a part of my code how I wrote it
Main ViewController:
import UIKit
class RecivingViewController: UIViewController, SendDataBack, SendDataBack2, SendDataBack3, SendDataBack4 {
#IBOutlet weak var recivingData: UILabel!
#IBOutlet weak var recivingData2: UILabel!
#IBOutlet weak var recivingData3: UILabel!
#IBOutlet weak var recivingData4: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func userData(data: String) {
recivingData.text = data
}
func userData2(data: String) {
recivingData2.text = data
}
func userData3(data: String) {
recivingData3.text = data
}
func PickerData(data: String){
recivingData4.text = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "view1" {
let SendingVC: SendingViewController = segue.destination as! SendingViewController
SendingVC.delegate = self
}
if segue.identifier == "view2" {
let SendingVC2: Sending2ViewController = segue.destination as! Sending2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "view3" {
let SendingVC3: Sending3ViewController = segue.destination as! Sending3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "picker" {
let SendingVC4: PickerViewController = segue.destination as! PickerViewController
SendingVC4.delegate = self
}
}
}
one of the other ViewControllers:
import UIKit
protocol SendDataBack {
func userData(data: String)
}
class SendingViewController: UIViewController {
#IBOutlet weak var DataTxt: UITextField!
var delegate: SendDataBack? = nil
#IBAction func done(_ sender: Any) {
if delegate != nil {
if DataTxt.text != nil {
let data = DataTxt.text
delegate?.userData(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
In order to see data after app is restarted you should use user defaults.
For saving data
UserDefaults.standard.set(newValue, forKey: "data")
For loading data in your view controller, if it's first load, when data is nil
UserDefaults.standard.string(forKey: "data")
Im still new to OSX / Swift 3.1 but Im a little stumped, Ive build an epos system and its work all fine, Im just stuck with printing out the receipt.
I have build a XIB View and the corresponding swift file for it show below
class Receipt: NSView {
let currentOrder = NewOrder.instance
#IBOutlet var view: NSView!
#IBOutlet weak var facebookString: NSTextField!
#IBOutlet weak var websiteString: NSTextField!
#IBOutlet weak var totalString: NSTextField!
#IBOutlet weak var vatString: NSTextField!
#IBOutlet weak var subTotalString: NSTextField!
#IBOutlet weak var CashierName: NSTextField!
#IBOutlet weak var orderNumber: NSTextField!
#IBOutlet weak var date: NSTextField!
#IBOutlet weak var itemList: NSTextField!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
Bundle.main.loadNibNamed("ReceiptView", owner: self, topLevelObjects: nil)
let contentFrame = NSMakeRect(0, 0, frame.size.width, frame.size.height)
self.view.frame = contentFrame
self.addSubview(self.view)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
subTotalString.stringValue = "Hello World"
view.draw(dirtyRect)
subTotalString.draw(dirtyRect)
}
}
I have added the nib name to the XIB reference and loaded a new Receipt() class and added the view to the NSPrintOperation.
let order = NewOrder.instance
let sview = Receipt()
let printer = NSPrinter(name: "EPSON TM-T88V");
let printData = NSPrintInfo()
printData.printer = printer!
let printerName = printer?.name
let docSize = NSMakeSize(CGFloat(204.0), CGFloat(200));
let res = "180x180dpi";
let speed = "Auto";
let blank = "Off";
let paperCut = "DocFeedCut";
let chashDrwr1 = "After";
let chashDrwr2 = "Off";
let buzzerControl = "Off";
let buzzerPattern = "Internal";
let buzzerRepeat = "1";
let data = TMPrintSupport.tmSetJobTicket(printData, printerName: printerName, documentSize: docSize, resolution: res, speed: speed, blank: blank, paperCut: paperCut, chashDrwr1: chashDrwr1, chashDrwr2: chashDrwr2, buzzerControl: buzzerControl, buzzerPattern: buzzerPattern, buzzerRepeat: buzzerRepeat)
let po = NSPrintOperation(view: sview.view, printInfo: printData)
// po.showsPrintPanel = false
po.canSpawnSeparateThread = true
po.cleanUp()
return po.run()
When the print view is shown it is blank and does not contain the view and is blank, I've also test printed and the print is just blank.
Any suggestions welcome, thanks
I am trying to change the textColor.Though I enter the numbers correctly into the textfields,it is working only for "else" condition but not for 'if'. Here is my code.
Can anyone fix this issue. Thanks
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var questionOne: UILabel!
#IBOutlet weak var fieldOne: UITextField! // textFields should be set as labels
#IBOutlet weak var questionTwo: UILabel!
#IBOutlet weak var fieldTwo: UITextField!
#IBOutlet weak var questionThree: UILabel!
#IBOutlet weak var fieldThree: UITextField!
#IBOutlet weak var questionFour: UILabel!
#IBOutlet weak var fieldFour: UITextField!
#IBAction func submitButton(sender: UIButton) {
fieldOneColorChange()
fieldTwoColorChange()
fieldThreeColorChange()
fieldFourColorChange()
}
#IBAction func resetButton(sender: UIButton) {
}
// Text color changes
func fieldOneColorChange() {
if fieldOne == 1 {
questionOne.textColor = UIColor.redColor()
} else {
questionOne.textColor = UIColor.blueColor()
}
}
func fieldTwoColorChange() {
if fieldTwo == 2 {
questionTwo.textColor = UIColor.brownColor()
} else {
questionTwo.textColor = UIColor.redColor()
}
}
func fieldThreeColorChange(){
if fieldThree == 3 {
questionThree.textColor = UIColor.blueColor()
} else {
questionThree.textColor = UIColor.purpleColor()
}
}
func fieldFourColorChange(){
if fieldFour == 4 {
questionFour.textColor = UIColor.blueColor()
} else {
questionFour.textColor = UIColor.redColor()
}
}
Change your if statement like this
if fieldOne.text=="1"
so on for every if statement respectively
For one of my static labels on my main story board, it prints out "Optional("United States"). However, I would like it to print out "United States". So my question is, how do I get rid of the "Optional" part? I've already tried doing:
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
I think the exclamation mark is supposed to "unwrap" some value right? However, even if I do p = placemarks!.first, it prints out "Optional("United States").
Below is the rest of my code just in case you would like some context:
//
// ViewController.swift
// Map Demo Rob 2
//
// Created by Jae Hyun Kim on 8/17/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var latitudeLabel: UILabel!
#IBOutlet weak var longitudeLabel: UILabel!
#IBOutlet weak var courseLabel: UILabel!
#IBOutlet weak var speedLabel: UILabel!
#IBOutlet weak var altitudeLabel: UILabel!
#IBOutlet weak var addressLabel: UILabel!
var manager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let userLocation: CLLocation = locations[0]
self.latitudeLabel.text = "\(userLocation.coordinate.latitude)"
self.longitudeLabel.text = "\(userLocation.coordinate.longitude)"
self.courseLabel.text = "\(userLocation.course)"
self.speedLabel.text = "\(userLocation.speed)"
self.altitudeLabel.text = "\(userLocation.altitude)"
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {(placemarks, error) -> Void in
print(userLocation)
if error != nil {
print(error)
return
}
else {
if let p = placemarks?.first{
self.addressLabel.text = "\(p.country)"
}
}
})
}
}
In
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
p.country is an Optional<String>. You need to unwrap that aswell in order to output only it's content (if it exists).
if let country = placemarks?.first?.country {
self.addressLabel.text = country
}