新行命令(\ n)不使用Firebase Firestore数据库字符串

时间:2018-02-12 21:24:52

标签: swift string firebase newline google-cloud-firestore

我正在使用Swift制作应用,而我正在使用Firebase Firestore。 Firestore是一个数据库,其中包含一些我放入UILabel的字符串。我的一些叮咬,我正在使用新的行命令(或\n)。所以我的一些字符串看起来像这样:

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

但是,无论何时检索到该字符串,它都会UILabel并且看起来像这样......

这是第一行\ n这是第二行\ n这是第三行

......应该是这样......

这是第一行

这是第二行

这是第三行

我假设\n不适用于来自数据库的字符串?我已尝试使用\\n进行双重转义。有人有解决方法吗?

以下是我正在使用的代码......

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

8 个答案:

答案 0 :(得分:6)

我明白了。我只是简单地替换了角色" \ n"从我使用newline命令收到的字符串。

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

因为我手动输入了我的字符串并给Firebase带来了刺痛感 "Line one\nline two\nline three"我正在替换" \ n"用" \ n"但是如果你给Firebase一个像

这样的字符串
"Line one
Line two
Line three"

Firebase用"\\n"替换这些返回值,然后生成代码

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

希望有所帮助!

答案 1 :(得分:1)

Firestore不支持字符串值中的任何转义序列。如果你在一个字符串中写“\ n”,那么当你阅读它时,你会得到完全的回复。如果您需要存储特殊内容,您可能需要自己编码和解码。

答案 2 :(得分:0)

对我来说,firebase将所有\ n都变成了\\\\ n,所以我只用了以下更改:

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

仅仅发布是因为我浪费了一些时间来计算正确的'\'

答案 3 :(得分:0)

Firestore添加此类型----第一行\第二行\第三行

获取Sting,替换为TextView并显示

String sura = modellist.get(position).getSura()。replace(“ \ n”,“ \ n”);

工作..

答案 4 :(得分:0)

我发现我可以使用String.fromCharCode()函数将换行符添加到firestore字段中。 Firestore似乎需要字符串中的特殊字符作为实际字符ASCII值,并且不会重新解释转义字符。

“第一行” + String.fromCharCode(13)+“第二行”

答案 5 :(得分:0)

尝试了所有建议的答案,但没有一个对我有用。最后,我在Firestore记录中使用了"/n",并在Swift客户端中使用了以下内容来修复它:

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

答案 6 :(得分:0)

100% 工作

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());
    }
});

希望对你有用

答案 7 :(得分:0)

您可以为 \n 使用 CSS 空白属性,它对我有用。

white-space: pre-line;