Home > Enterprise >  How to add data to a specific uid in Firestore Database?
How to add data to a specific uid in Firestore Database?

Time:11-13

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.

CodePudding user response:

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
    }
}

CodePudding user response:

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 ?? ""]
}
  • Related