If I just use the text field and run the app I can enter data in the text field and it stores in the Firebase database but when I close the application the data is gone from the text box , better yet it does not show in the UItextbox, i can type it and click submit to send the information to the server. So how can I show it again after the application is closed and reopened. I am using the cloud store in Firebase btw and using swift to code it in xcode
class viewcontroller5: UIViewController{
#IBOutlet weak var HowManyTextfield: UITextField!
#IBOutlet weak var WhatBrandTextField: UITextField!
#IBOutlet weak var HowOftenTextField: UITextField!
#IBOutlet weak var SubmitButton: UIButton!
// set document refenrence
let db = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeAction(swipe:)))
swipeRight.direction = UISwipeGestureRecognizer.Direction.right
self.view.addGestureRecognizer(swipeRight)
}
// Function to get the auto generated document ID
func getDocument(){
let docData : [String:Any] = [
"LastUpdated":FieldValue.serverTimestamp(),
"HoursOfSleep": HowManyTextfield.text! as String,
"BrandOfProducts": WhatBrandTextField.text! as String,
"HowManyTrims":HowOftenTextField.text! as String
]
guard let userID = Auth.auth().currentUser?.uid else {return}
// print(userID)
db.collection("Users").whereField("UID", isEqualTo: userID).getDocuments(){ (querySnapshot, err) in
if let err = err {
print(err.localizedDescription)
return
} else{
for document in querySnapshot!.documents{
if document == document{
print(document.documentID)
//create a profile collection and add the new information
let Profile = self.db.collection("Users").document(document.documentID)
Profile.updateData(docData){
err in
if let err = err{
print("error updating document: \(err)")} else { print("Document sucessfully updated")}
}
}
}
}
}
}
#IBAction func SubmitButton(_ sender: UIButton) {
globalDashboardVC?.FirstPage()
getDocument()
}
}
Related
I would like some help with the coding on how to store data into a specific user after the user have successfully logged in. Below are the codes for the page where user can input the details of their new readings.
import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore
class NewBookViewController: UIViewController {
#IBOutlet weak var bookTitleTextField: UITextField!
#IBOutlet weak var bookAuthorTextField: UITextField!
#IBOutlet weak var bookSummaryTextField: UITextField!
#IBOutlet weak var ratingController: UIView!
#IBOutlet weak var newBookCancelButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
func validateFields() -> String? {
if
bookTitleTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
bookAuthorTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
bookSummaryTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all the fields."
}
return nil
}
#IBOutlet weak var newBookSaveButton: UIButton!
var ref = Firestore.firestore()
#IBAction func newBookSaveButtonTapped(_ sender: Any) {
let uid = Auth.auth().currentUser?.uid
self.ref?.child("new reading").child(uid).setValue(post)
func post() {
let bookTitleTextField = "bookTitle"
let bookAuthorTextField = "bookAuthor"
let bookSummaryTextField = "bookSummary"
let post : [String : AnyObject] = [ "bookTitle" : bookTitleTextField as AnyObject, "bookAuthor" : bookAuthorTextField as AnyObject, "bookSummary" : bookSummaryTextField as AnyObject]
}
this is the successful user sign up on cloud firestore. after the user have logged in, I wanted to add those 3 data (title, author, summary) FOR the specific user.
It looks like you're close. Right now, you aren't returning anything from post, though. I think you also mean to be getting the text values from each UITextField instead of just declaring Strings with the names of the fields.
#IBAction func newBookSaveButtonTapped(_ sender: Any) {
guard let uid = Auth.auth().currentUser?.uid else {
//handle your error here
return
}
self.ref?.child("new reading").child(uid).setValue(post())
}
func post() -> [String:String] {
return ["bookTitle" : bookTitleTextField.text ?? "",
"bookAuthor" : bookAuthorTextField.text ?? "",
"bookSummary" : bookSummaryTextField.text ?? ""]
}
You should take a much safer approach to handling the user's ID and the values of the text fields. Here, the data is only written to the database if the user is logged in and all 3 of the text fields have strings in them. I don't know what collection you intended to place this document in so I went with what you wrote but I suspect it isn't right.
class NewBookViewController: UIViewController {
private let db = Firestore.firestore()
#IBAction func newBookSaveButtonTapped(_ sender: Any) {
guard let uid = Auth.auth().currentUser?.uid,
let data = bookData() else {
return
}
db.collection("new reading").document(uid).setData(data)
}
// This returns an optional dictionary (nil when the data is incomplete).
// This is entirely optional (pun) but I suspect you don't want
// empty fields in these database documents.
func bookData() -> [String: Any]? {
guard let title = bookTitleTextField.text,
let author = bookAuthorTextField.text,
let summary = bookSummaryTextField.text else {
return nil
}
let data: [String: Any] = [
"bookTitle": title,
"bookAuthor": author,
"bookSummary": summary
]
return data
}
}
This question already has answers here:
"Value of type 'AuthDataResult' has no member 'uid'" error
(3 answers)
Closed 1 year ago.
how's everyone? I hope you're safe and well!
I'm studying SWIFT and problem came across and honestly I don't have a clue i how to solve it. Can any one help me?
Here is the code bellow:
import UIKit
import Firebase
class CreateUserVC: UIViewController {
#IBOutlet weak var emailTxt: UITextField!
#IBOutlet weak var passwordTxt: UITextField!
#IBOutlet weak var userNameTxt: UITextField!
#IBOutlet weak var createBtn: UIButton!
#IBOutlet weak var cancelBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
createBtn.layer.cornerRadius = 10
cancelBtn.layer.cornerRadius = 10
// Do any additional setup after loading the view.
}
#IBAction func createUserTapped(_ sender: Any) {
guard let email = emailTxt.text,
let password = passwordTxt.text,
let userName = userNameTxt.text else { return }
Auth.auth().createUser(withEmail: "", password: "", completion: { (user, error) in
if let error = error {
debugPrint("Error creating user: \(error.localizedDescription)")
}
let changeRequest = user.profileChangeRequest()
changeRequest?.displayName = userName
changeRequest?.commitChanges(completion: {(error) in
})
})
}
#IBAction func cancelTapped(_ sender: Any) {
}
}
enter image description here
The completion block of Auth.auth.createUser isn't invoked with a User object but with an optional AuthDataResult object. So you need to check that the operation was successful by checking AuthDataResult isn't nil, retrieve the user object from it, then start your profileChangeRequest:
Auth.auth().createUser(withEmail: "", password: "", completion: { (result, error) in
guard let user = result?.user else {
if let error = error {
debugPrint("Error creating user: \(error.localizedDescription)")
} else {
debugPrint("Error creating user: unknown error")
}
return
}
let changeRequest = user.profileChangeRequest()
changeRequest?.displayName = userName
changeRequest?.commitChanges(completion: {(error) in
})
})
I'm writing an App, that takes information from an Excel document and saves the Data in Realm. My problem is, that every time I open the App, the Realm Database will save a copy of the Information. Now I get my TableViews with 3 times the same items.
Here is the code in my Main View Controller:
class ViewController: UIViewController {
let realm = try! Realm()
var importExcel = Import()
var xslxConvert = xslxConverter()
var currentString: [String] = []
var Name = ""
#IBOutlet weak var VRLabel: UIButton!
#IBOutlet weak var configurationLabel: UIButton!
#IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
currentString = importExcel.Results()
Label.text = Name
DispatchQueue.main.async {
self.saveData()
print("Data from Excel saved")
}
}
//MARK: - SaveData to the Realm
func saveData() {
do {
try realm.write {
for item in currentString {
let newItem = FunctionData()
newItem.functionName = item
realm.add(newItem)
}
}
} catch {
print ("Error trying to Realm data, \(error)")
}
}
}
How can I make a filter of something, to make that the App just save the Information from Excel ones?
Thanks a lot for the help!
Ok, I think it doesn't work with UUID(), because it will be different all time.
let filter = // choose what you need
if let items = Array(realm.objects(FunctionData.self).filter("parameterName == %#", filter)) {
// Do not save
} else {
// Save
}
And try to use realm.add(newItem, update: .modified) for saving
I have made an sign up and also login and it works! but now I want to edit the data in the Firebase. Can anyone help me how to do it? Thanks you
Here the Sign Up View Controller
import UIKit
import FirebaseAuth
import FirebaseFirestore
class SignupViewController: UIViewController {
#IBOutlet weak var FirstNameTextfield: UITextField!
#IBOutlet weak var LastNameTextfield: UITextField!
#IBOutlet weak var EmailTextField: UITextField!
#IBOutlet weak var PasswordTextfield: UITextField!
#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 validateFields()->String? {
//check that all the fields are fill
if FirstNameTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || LastNameTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || PasswordTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
{
return "Please fill up all the Fields"
}
//check the password if the password is secure
let cleanedPassword = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false{
return "Please enter at least 8 characters, with a number and characteristic symbol"
}
return nil
}
#IBAction func SignUpTap(_ sender: Any) {
let error = validateFields()
if error != nil{
showError(message: error!)
}
else {
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)
Auth.auth().createUser(withEmail: Email, password: Password) { (result, err) in
if err != nil{
self.showError(message: "Error creating the user")
}
else {
let db = Firestore.firestore()
db.collection("users").addDocument(data:["FirstName":FirstName, "LastName":LastName, "uid": result!.user.uid]) { (Error) in
if error != nil{
self.showError(message: "Cannot saving user data" )
}
}
self.transitionToHomePage()
}
}
}
}
func showError( message:String){
ErrorLabel.text = message
ErrorLabel.alpha = 1
}
func transitionToHomePage(){
let TabHomeViewController = storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? TabHomeViewController
view.window?.rootViewController = TabHomeViewController
view.window?.makeKeyAndVisible()
}
}
Here my login VC
#IBAction func LoginTap(_ sender: Any) {
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Password = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().signIn(withEmail: Email, password: Password) { (result, error) in
if error != nil{
self.ErrorLabel.text = error!.localizedDescription
self.ErrorLabel.alpha = 1
}
else{
let TabHomeViewController = self.storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? UITabBarController
self.view.window?.rootViewController = TabHomeViewController
self.view.window?.makeKeyAndVisible()
}
And here my Account View Controller
import UIKit
import FirebaseAuth
import FirebaseFirestore
import Firebase
class AccountViewController: UIViewController {
#IBOutlet weak var FNameTextField: UITextField!
#IBOutlet weak var LNameTextField: UITextField!
#IBOutlet weak var EmailTextField: UITextField!
#IBOutlet weak var PasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func logoutbutton(_ sender: Any) {
do{
try Auth.auth().signOut()
performSegue(withIdentifier: "signout", sender: nil)
}
catch{
print(error)
}
}
}
You can use this function:
func updateFirestoreUserProfile(uid: String, data: [String:Any]) {
Firestore.firestore().collection("users").document(uid).updateData(data) { err in
if let err = err {
print("Error updating document: \(err) ")
}
else {
print("Document successfully updated")
}
}
}
You can use the function like this:
let data = [
"FirstName": name,
"LastName": surname
]
updateFirestoreUserProfile(uid: user.uid, data: data)
I have my upload code here
import UIKit
import Firebase
class ChatViewController: UIViewController {
let chatRef = FIRDatabase.database().reference().child("chat")
let userUid = FIRAuth.auth()?.currentUser?.uid
var userName = ""
#IBOutlet weak var topBar: UINavigationItem!
#IBOutlet weak var containerView: UIView!
#IBOutlet var inputTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
topBar.title = "Chat Log Controller"
FIRDatabase.database().reference().child("users/\(userUid!)/name").observe(.value) { (snap: FIRDataSnapshot) in
self.userName = (snap.value! as! String).description
}
}
#IBAction func handleSend(_ sender: AnyObject) {
let childChatRef = chatRef.childByAutoId()
let message = inputTextField.text!
childChatRef.child("text").setValue(message)
print(inputTextField.text)
}
#IBAction func handleSendByEnter(_ sender: AnyObject) {
let childChatRef = chatRef.childByAutoId()
let message = inputTextField.text!
print(userName)
childChatRef.child("name").setValue(userName)
childChatRef.child("text").setValue(message)
print(inputTextField.text)
}
}
text is successfully uploaded But
It doesn't print userName and doesn't upload it to Firebase Database
But username is nut nil!
Try to use your observer code as,
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
}
Just take self.username = snap.value! as! String
It will solve your problem.