如何在 rtf 文件中写入 NSAttributedString?

How can I write NSAttributedString in rtf file?

如何在rtf文件中写入NSAttributedString?我找到了一个古老的答案 How can I save the attributed string (text) into file (swift, cocoa)? 我不太明白我到底需要什么,也许某处存在新的不同方式?

Swift 4

do {
    let attributedString = try NSAttributedString(url: fileURL, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
} catch {
    print("\(error.localizedDescription)")
}

您可以使用 NSAttributedStringdata(from:) 方法将您的属性字符串转换为 rtf 数据。

extension NSAttributedString {
    func rtf() throws -> Data {
        try data(from: .init(location: 0, length: length),
            documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf,
                                 .characterEncoding: String.Encoding.utf8])
    }
}

let textView = UITextView()
textView.attributedText = .init(string: "abc",
                                attributes: [.font: UIFont(name: "Helvetica", size: 16)!])
do {
    let rtfURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("RichTextDocument.rtf")
    try textView.attributedText.rtf().write(to: rtfURL)
    print("saved")
} catch {
    print(error)
}