KoolKid
KoolKid

Reputation: 45

Using Firebase in Swift, how can I pull documents from a collection to be displayed in a text view?

After logging into the app, in a settings page, SettingsViewController, I would like for the user to be able to see their information in a text view. However, no matter the approach to reading the data, i always get the Swift Compiler Warning:

Cast from '[String]' to unrelated type 'String' always fails

This is my code:

func textViewFill() {

    let db = Firestore.firestore()

    db.collection("users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                let firstName = ["firstName"] as? String ?? ""
                let lastName = ["lastName"] as? String ?? ""
                let email = ["email"] as? String ?? ""
                self.firstNameTextView.text = firstName
                self.lastNameTextView.text = lastName
                self.emailTextView.text = email
            }
        }
    }
}

The warning appears for when I am trying to define the documents as strings:

let firstName = ["firstName"] as? String ?? ""
let lastName = ["lastName"] as? String ?? ""
let email = ["email"] as? String ?? ""

Is there no way to display it as text?

Upvotes: 4

Views: 43

Answers (2)

Jawad Ali
Jawad Ali

Reputation: 14397

You can use if let to unwrap optionals and dont cast Array as string .. it will always fails..

 func textViewFill() {

    let db = Firestore.firestore()

    db.collection("users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            if let document = querySnapshot!.documents.first {
                print("\(document.documentID) => \(document.data())")
                if  let firstName = document.get("firstName") as? String ,
                    let lastName = document.get("lastName") as? String,
                    let email = document.get("email") as? String {

                    self.firstNameTextView.text = firstName
                    self.lastNameTextView.text = lastName
                    self.emailTextView.text = email
                }

            }
        }
    }
}

Upvotes: 1

Frankenstein
Frankenstein

Reputation: 16341

You're trying to cast an Array as String here. Here's what you need:

let firstName = document.get("firstName") as? String ?? ""
let lastName = document.get("lastName") as? String ?? ""
let email = document.get("email") as? String ?? ""

Upvotes: 3

Related Questions