22

I'm making an app with Swift and I'm using Firebase Firestore. Firestore is a database that has some strings that I put into a UILabel. With some of my strings, I am using the new line command (or \n). So some of my strings look like this:

"This is line one\nThis is line two\nThis is line three"

But, whenever that string is retrieved, it's addetoto the UILabel and appears like this...

This is line one\nThis is line two\nThis is line three

...when it should be like this...

This is line one

This is line two

This is line three

I'm assuming that \n does not work with strings coming from a database? I've tried double escaping with \\n. Does anyone have a fix for this?

Here is the code that I am using...

    database.collection("songs").whereField("storyTitle", isEqualTo: "This is the story header").getDocuments { (snapshot, error) in
        
        for document in (snapshot?.documents)! {
            self.storyBodyLabel.text = (document.data()["storyBody"] as? String)!
   }
}
9
  • Have you tried double escaping it (eg. \\n)?
    – l'L'l
    Feb 12, 2018 at 21:26
  • @l'L'l Yes, I have. Feb 12, 2018 at 21:31
  • 1
    As Doug answered: the Firebase Database doesn't modify your strings in any way. If you store a \n, it will be there when you read it back. But if that doesn't translate into a newline in your UILabel that problem is likely later in the code. It will be a lot easier to help if you create an MCVE, which includes code that 1) saves the string, 2) loads the string, 3) sets the string to a UILabel. Feb 12, 2018 at 21:43
  • @FrankvanPuffelen Ok. Just updated my question. The string is already in the database, so there is no saving process. Feb 12, 2018 at 22:05
  • 1
    Yeah, you are putting literal characters "\n" in there. It doesn't work like that - see my answer. Feb 12, 2018 at 22:51

10 Answers 10

20

I got it. I simply just replaced the character "\n" from the string that I was receiving with the newline command.

label.text = stringRecived.replacingOccurrences(of: "\n", with: "\n")

Because I manually typed out my string and gave Firebase a string like "Line one\nline two\nline three" I am replacing "\n" with "\n" But if you give Firebase a string like

"Line one
Line two
Line three"

Firebase replaces those returns with "\\n" therfore making the code

label.text = stringRecived.replacingOccurrences(of: "\\n", with: "\n")

Hope that helps!

3
  • 14
    Are you sure you are replacing \n? Firebase converts \n into \\n so you need to convert back with stringRecived.replacingOccurrences(of: "\\n", with: "\n") Mar 1, 2018 at 14:29
  • Rufat Mirza has the right answer for this issue!, thanks for your comment Aug 7, 2018 at 15:08
  • 1
    Thank you for answer! Now the command is stringRecived.replaceAll(RegExp(r'\\n'), '\n')
    – awaik
    Sep 4, 2019 at 20:31
2

You can use CSS whitespace property for \n, it works for me.

white-space: pre-line;
1
  • yes it does work. Also if we use tilde `` it works awesome.
    – Santosh
    Sep 20, 2022 at 7:24
2

Solution: Add this to your string and you are done (for Java users):

.replace("\\n", "\n")

Example:

    if (dataSnapshot.exists())
    {
    ArrayList<String> userlogs2 = new ArrayList<String>();
    userlogs2.add(dataSnapshot.getValue().toString().replace("\\n", "\n"));
    
    Iterator<String> it2 = userlogs2.iterator();
    

    while (it2.hasNext()) {
    
    appendColoredText(userlogsmessages2, it2.next() + "\n", Color.BLACK);
    
    appendUnderlinedText(userlogsmessages2,"____________" + "\n\n", Color.parseColor("#DB808080"));
    
                                    }
1

Firestore doesn't support any escape sequences within string values. If you write "\n" in a string, you're going to get exactly that back when you read it. If you need to store something special, you may want to encode and decode that yourself.

7
  • Do you mean "Firebase Realtime Database doesn't support newline characters [and some other characters]"? Database storage and string literals are separate issues. Feb 12, 2018 at 22:03
  • No, you can put whatever characters you want in Firestore. I even put emoji in there recently. You just can't expect Firestore to understand any sort of character escape sequences that might have meaning in programming languages. twitter.com/CodingDoug/status/961302822997213184 Feb 12, 2018 at 22:50
  • @DougStevenson I'm sorry. I'm fairly new to coding. How would I do this? Feb 12, 2018 at 22:55
  • That sounds like a different question to ask here on Stack Overflow. Feb 12, 2018 at 22:58
  • @DougStevenson Ok. I'll look and see if anyone else has asked. I'm sure they have. Thanks for your help! 👍🏻 Feb 12, 2018 at 22:59
1

Tried all of the answers suggested but none worked for me. In the end, I fixed it by using "/n" in the Firestore record and, in the Swift client, the following:

label.text = stringReceived.replacingOccurrences(of: "/n", with: "\n")
0

For me firebase turned all \n to \\\\n , so I just reversed that change with :

theString.replaceAll( "\\\\n", "\n" );

Just posting cause I wasted some time calculating the right number of '\'

0

I found I could get newlines into a firestore field by using the String.fromCharCode() function. Firestore seems to need special characters in strings to be the actual character ASCII values and does not reinterpret escape characters.

i.e.

"First Line " + String.fromCharCode(13) + "second line"

0

100% Working

DB.collection(Global.DB_COLLECTION_PATH).document(NEWS_ID).get().addOnCompleteListener(new OnCompleteListener< DocumentSnapshot >() {
    @Override
    public void onComplete(@NonNull Task< DocumentSnapshot > task) {
        if (task.isSuccessful()) {
            body1 = task.getResult().getString("newsBody").replace("\n", "\n");
            nBody.setText(body1);
        }
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Log.e("DB FAILED", e.getMessage());
    }
});

I hope it's work for you

0

I noticed that when you add a string with \n to the JSON export and then upload the JSON to the Realtime Database, it acts as a newline. But if you edit that from the firebase console, it gives you back the string with \n and not a newline.

-1

Firestore add this type----Line one\nline two\nline three

get Sting, replace and show with TextView

String sura=modellist.get(position).getSura().replace( "\n", "\n");

Working..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.