unable to save files to firebase - swift

I am trying to make an app that uses firebase for authentication and database. This is my first app using firebase and I am unable to save files to firebase database. I am not getting any error in the console when I run the app but it is not saving anything to firebase. I read the firebase docs and followed the instruction but I am unable to get it to work. Help would be appreciated. Here is my code
import UIKit
import Firebase
import FirebaseDatabase
class AddVC: UIViewController {
var refAttractions: DatabaseReference! //defining firebase database reference
#IBOutlet weak var addedlbl: UILabel!
#IBOutlet weak var descriptioninfo: UITextField!
#IBOutlet weak var categoryinfo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// accessing nodes of refAttractiions
refAttractions = Database.database().reference().child("Attractions")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func submitbtn(_ sender: Any) {
addAttractions()
}
func addAttractions(){
let key = refAttractions.childByAutoId().key //creating id for the attraction.
let attraction = ["id": key,
"category": categoryinfo.text! as String,
"description": descriptioninfo.text! as String ]
refAttractions.child(key).setValue(attraction)
}
#IBAction func backbtn(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
Also, I have changed the rules in my firebase database to true for both read and write. Any help would be appreciated.

Related

(Swift) Save data from UITextField into Firebase Firestore

Currenty the code shown saves the String "TEST" in the Firestore database. What I need to have happen is for the text entered into the UITextField to be saved when the buttons pressed and that data be saved in the Firestore database.
For my IBAction func, I believe that it is correct but I do not know how to take the train variable and place it in my dict without getting an error.
import Foundation
import UIKit
import Firebase
import FirebaseUI
class TrainViewController: UIViewController{
#IBOutlet weak var trainField: UITextField!
#IBOutlet weak var locationField: UITextField!
#IBOutlet weak var engineField: UITextField!
#IBAction func saveButton(_ sender: UIButton) {
var train: String = trainField.text!
}
override func viewDidLoad() {
super.viewDidLoad()
trainField.delegate = self
var dict = [String:String]()
dict.updateValue("TEST", forKey: "train")
let db = Firestore.firestore()
db.collection("users").addDocument(data: dict)
}
}
extension TrainViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
You may want to collect the string from the field in the action and then pass it to a function for saving.
class TrainViewController: UIViewController{
#IBOutlet weak var trainField: UITextField!
#IBOutlet weak var locationField: UITextField!
#IBOutlet weak var engineField: UITextField!
#IBAction func saveButton(_ sender: UIButton) {
let trainText = trainField.text!
self.saveText(theText: trainText)
}
override func viewDidLoad() {
super.viewDidLoad()
}
func saveText(theText: String) {
let db = Firestore.firestore()
let dict = ["train_text": theText]
db.collection("users").addDocument(data: dict)
}
}
Will result in the following being written to Firestore
your_firestore
users
random_doc_id
train_text: "the passed in string"
EDIT
Based on some new info, the OP would like to take the text from three text fields and write them all to a single document.
So change the button action thusly - all it does is calls our saveText function and does not pass any data.
#IBAction func saveButton(_ sender: UIButton) {
self.saveText()
}
then the saveText function
func saveText() {
let trainText = self.trainField.text!
let locationText = self.locationField.text!
let engineText = self.engineField.text!
let db = Firestore.firestore()
let dict = ["train_text": trainText,
"location_text": locationText,
"engine_text": engineText]
db.collection("users").addDocument(data: dict)
}
and the resulting Firestore looks like this
your_firestore
users
random_doc_id
train_text: "text from the train field"
location_text: "text from the location field"
engine_text: "text from the engine field"
This is fairly simple to achieve, what you need to do is declare a function that saves the data after it's entered.
The reason you aren't able to save the trainField is because when the ViewController calls viewDidLoad the button hasn't been pressed, therefor you aren't getting the text from the trainTextField.
To solve this you can do the following:
fileprivate func saveTrainWithData(text: String) {
let dictData = ["train": text] as [String:Any]
// save data to FireStore here using `dictData`
let db = Firestore.firestore()
db.collection("users").addDocument(data: dictData)
}
Now to fire this function off just call it inside of the #IBAction as shown below
#IBAction func saveButton(_ sender: UIButton) {
var train: String = trainField.text!
saveTrainWithData(text: train)
}

How to access a text field value and convert to double

I am working on trying to build a tip calculator using swift but am running into a multitude of problems. I have a text box where the user enters in the bill amount and then they can adjust a slider to indicate the percentage that they want to tip. I have managed to get the slider and label associated with it to work where changing the value on the slider changes the label. However, I can't figure out how to get the text field to work. I attempted to create an action for the bill amount text box being changed but no matter what I put in it, it doesn't seem like the code is ever being executed (Whenever I run the code and click in the text box, the keyboard won't go away so maybe this is part of the problem?). All that I need is to be able to access the value in the text box field inside of my action when I click the calculate button but I can't seem to even get the value to show up much less convert it to a double so I can perform calculations on it. I am super new to swift and really want to learn what I am doing wrong. I have tried multiple tutorials and similar questions on here but none of them work. I appreciate all help y'all can give.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtBillAmount: UITextField!
#IBOutlet weak var lblTipPercentage: UILabel!
#IBOutlet weak var sldTipPercentage: UISlider!
#IBOutlet weak var lblTipAmount: UILabel!
#IBOutlet weak var lblTotalAmount: UILabel!
var tipPercentage = 10
var billAmount = ""
#IBAction func valueChanged(sender: AnyObject) {
let currentValue = Int(sldTipPercentage.value)
lblTipPercentage.text = "\(currentValue)%"
tipPercentage = currentValue
}
#IBAction func btnCalculate(sender: AnyObject) {
lblTipAmount.text = "\(billAmount)"
}
#IBAction func txtBillAmountValueChanged(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
//txtBillAmount.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func btnReset(sender: UIButton) {
sldTipPercentage.value = 10
lblTipPercentage.text = "10%"
txtBillAmount.text = ""
lblTipAmount.text = "--"
lblTotalAmount.text = "--"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is a screenshot of how the UI looks
Error that I am getting
[Xcode >= 7 and Swift > 2]
Try like this
#IBAction func btnCalculate(sender: AnyObject) {
if let textValue = txtBillAmount.text {
let billAmnt = Double(textValue)
let tipAmount = (billAmnt*tipPercentage)/100
lblTipAmount.text = "\(tipAmount)"
}
}
If you are using Xcode-6 and Swift < 2 then try the following way. because String initializer for Double is only available in Swift 2 (Xcode 7). [Recommend update your Xcode]
#IBAction func btnCalculate(sender: AnyObject) {
let billAmnt = (txtBillAmount.text! as NSString).doubleValue
let tipAmount = (billAmnt*tipPercentage)/100
lblTipAmount.text = "\(tipAmount)"
}

How do I check if x is in a variable in classes within a list?

I have a list called mainframe which holds classes. I want to check before adding a new username; if newusername is in mainframe.usernames perform adding the new username in.
pretty much something like this:
import UIKit
class addNewPassword: UIViewController {
var homeVC = Home()
#IBOutlet weak var createHolderItem: UITextField!
#IBOutlet weak var createHolderUsername: UITextField!
#IBOutlet weak var createHolderPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func savePasswordButton(_ sender: Any) {
let holder = Holder()
holder.item = createHolderItem.text!
holder.username = createHolderUsername.text!
holder.password = createHolderPassword.text!
}
if mainframe.contains(where: { $0.username == holder.username }) {
print("test")
}
else {
homeVC.mainframe.append(holder)
homeVC.tableView.reloadData()
navigationController?.popViewController(animated: true)
}
}
I pretty much want to run a loop, within an if statement. Or am I approaching it the wrong way?
I'm new to programming, did online tutorials and trying to write my first iOS app for my aunt.
if mainframe.usernames.contains(holder.username) {
...
Use contains :
if mainframe.usernames.contains(holder.username) {
...
}

Parse PFUser not registering subclass

I am trying to use Parse PFUser in a software for OSX desktop. When I try to use it PFUser.query() it gives a message: Failed to set (contentViewController) user defined inspected property on (NSWindow): The class PFUser must be registered with registerSubclass before using Parse.
It is happening without registering the class.
I tried it registering the class this way: PFUser.registerSubclass() but it still doesn't work.
I will use the default PFUser without adding any fields to it, so I don't need to create a custom class to be my PFUser.
I tried to use PFUser.enableAutomaticUser() without success
Code below:
AppDelegate.swift
import Cocoa
import Parse
import Bolts
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let APP_ID = "app_id"
let CLIENT_KEY = "client_key"
let SERVER = "https://parseserver.com/"
func applicationDidFinishLaunching(_ aNotification: Notification) {
PFUser.registerSubclass()
let configuracaoParse = ParseClientConfiguration {
$0.applicationId = self.APP_ID
$0.clientKey = self.CLIENT_KEY
$0.server = self.SERVER
}
Parse.initialize(with: configuracaoParse)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
ViewController.swift
import Cocoa
import Parse
class ViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var senhaSecureTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
contaUsuarios()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func entrarButtonClicked(_ sender: NSButton) {
}
func contaUsuarios() {
let query = PFUser.query()
query?.countObjectsInBackground(block: {
(count, error) -> Void in
let numeroUsers = Int(UInt32(count))
if numeroUsers > 0 {
}
print(numeroUsers)
})
}
}
Reading some content on the internet I discovered that in OSX the ViewController is launched before the AppDelegate finishes loading, so I initialized the Parse connection and subclassing in the ViewController's viewDidLoad instead of AppDelegate and it is working just fine.

Swift: access Variables from other classes in different swift files

I have tried to implement the solution from this answer but I just haven't been able to get it to work. I get 'Use of unresolved identifier...' for the variables I am trying to access..
I have a loginViewController.swift that gets the username and password when someone logs in..
import UIKit
class loginViewController: UIViewController {
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
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 loginButtonTapped(sender: AnyObject) {
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
Then I have a PostService.swift file that gets data from a MySQL database.. It should use the username of the person logged in to access the relevant data..
import Foundation
class PostService {
var settings:Settings!
let userEmail = "steve#centrix.co.za"; //This is hard coded but needs to come from the loginViewController
let userPassword = "1234"; //This is hard coded but needs to come from the loginViewController
I have tried that and a few other suggestions and I just don't seem to be able to get it to work.. Please help..
Thanks in advance.
You can just declare
var userEmail = "";
var userPassword = "";
outside a class (it doesn't matter which Swift class). Then, dropping the let,
#IBAction func loginButtonTapped(sender: AnyObject) {
userEmail = userEmailTextField.text;
userPassword = userPasswordTextField.text;
will store the variables, and you'll just be able to use the in the PostService class.
However, is there really no connection between the LoginViewController and the PostService? You'll have to call a PostService function somewhere ... maybe you can pass the variables there?