Home > OS >  Unable to fetch data in proper formatting from firebase firestore database xcode12.5 swift
Unable to fetch data in proper formatting from firebase firestore database xcode12.5 swift

Time:09-25

I want to get data with basic formatting in which I paste from my notes i.e texts in multiple lines but, when pasting the data into the firebase firestore database the entire data appears in a single line is there a way to fix it and have the data arranged in different lines instead of just placing then all in a single line.

Expected Result Covid 19 Measures

Final Result

Firebase Console Xcode Preview

CodePudding user response:

I suggest trying to add /n after the end of each line, but do not add a space after it.

i.e "Line1 /nLine2"

CodePudding user response:

This may not be THE answer but is it a solution. I did this on macOS, iOS will be similar.

I don't believe the Firebase console supports text formatting, so pasting a string removes all formatting.

However, writing a formatted string to Firestore using code is essentially three lines

   let myString = """
Hello, World on first line
This is a test on second line
This is the third line
"""
   let myCollection = self.db.collection("Covid19")
   myCollection.document("covid").setData(["duty": myString])

and then reading it back and printing to console

let myCollection = self.db.collection("Covid19")
let myDoc = myCollection.document("covid")
myDoc.getDocument(completion: { snapshot, error in
    let text = snapshot?.get("duty") as! String
    print(text)
})

and the output is

Hello, World on first line
This is a test on second line
This is the third line

But... while the line breaks are preserved, it looks like you have Rich Text as well. To store that, NSKeyedArchiver to the rescue.

NSKeyedArchiver will encapsulate the entire string, line breaks, formatting etc into a Data object which can then be stored in Firestore. Then when you need to display it in a TextView for example, read the data in and use NSKeyedUnarchiver

So here's the code to make rich text from a textView into Data object and store in Firestore

let myString = self.myTextView.attributedString()
let myCollection = self.db.collection("Covid19")
let d = try! NSKeyedArchiver.archivedData(withRootObject: myString, requiringSecureCoding: false)
myCollection.document("covid_2").setData(["duty": d])

and then reading it back in to display in a textView

let myCollection = self.db.collection("Covid19")
let myDoc = myCollection.document("covid_2")
myDoc.getDocument(completion: { snapshot, error in
    let d = snapshot?.get("duty") as! Data
    let attrText = try! NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: d)
    self.myTextView.textStorage?.append(attrText!)
})

I omitted all error checking so don't forget to add that.

  • Related