gpt4 book ai didi

ios - Swift 阅读 RTF 文件不适用标签

转载 作者:行者123 更新时间:2023-11-28 15:06:44 24 4
gpt4 key购买 nike

我正在读取一个 rtf 文件,但输出结果显示包含标签的简单字符串,它没有按应有的方式显示为 NSAttributedString这是我的代码

if let rtfPath = Bundle.main.url(forResource: "SampleHTML", withExtension: "rtf") {
do {
let attributedStringWithRtf: NSAttributedString =
try NSAttributedString(url: rtfPath, options: [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.rtf], documentAttributes: nil)
}catch let error {
print("Got an error \(error)")
}
}

读取文件后,其属性字符串显示为:
< p > < em>查看以下信息。然后选择最佳答案并点击提交。回答完毕后,点击下一题继续前进。


我在标签中插入了空格以澄清问题,没有空格 StackOverflow 将标签应用于文本,我在这里缺少什么?

最佳答案

在 RTF 到 NSAttributedString 之后你得到了(你可以使用 SO 的代码标签来避免解释 HTML 标签):

<p><em>Review the following information. Then select the best answer and click <strong>Submit</strong>. After answering, click <strong>Next Question</strong> to move forward.</em></p>

现在,您有一个 HTML AttributedString。
和 RTF 一样,有一种方法可以得到 NSAttributedString来自 HTML 字符串。因此,让我们首先获取 HTML 字符串:let htmlString = attributedStringWithRtf.string .
对于其余部分,方法与使用的方法几乎相同,但有变化:NSAttributedString.DocumentType.html而不是 NSAttributedString.DocumentType.rtf (看起来很明显),并且有一个带有 data 的初始化而不是路径,所以你只需要使用 let htmlData = htmlString.data(using:.utf8)

所以代码:

let rtfPath = Bundle.main.url(forResource: "SampleHTML", withExtension: "rtf") 
let attributedStringWithRtf: NSAttributedString = NSAttributedString(url: rtfPath, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
let htmlString = attributedStringWithRtf.string
let htmlData = htmlString.data(using:.utf8)
let attributedString: NSAttributedString = NSAttributedString(data: htmlData, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)

注意:我没有使用 if let , try/catch故意的,因为您已经正确使用了它们,而且我对您的问题背后的逻辑以及如何解决问题更感兴趣。

现在,在评论中讨论之后:您将 HTML 文本(即带有 HTML 标签)保存到 RTF 文件中。显然,这太过分了,因为正如您在我给您的解决方案中看到的那样,进行了两次转换以获得最终的 NSAttributedString。 .
所以,我要做的是完全使用 RTF 文件,并将 RTF 标签设置为等同于 <p> , <em> , <strong>等而不是 HTML 的。将 HTML 字符串(带有 HTML 标签)保存在一个简单的 .txt 中.

比如我用TextEdit.app保存了一个RTF文件,实际内容是:

{\rtf1\ansi\ansicpg1252\cocoartf1504\cocoasubrtf830
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0

\f0\fs24 \cf0 myText}

我刚刚写了myText , RTF加入了很多if own标签。

关于ios - Swift 阅读 RTF 文件不适用标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48336292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com