How can I write NSAttributedString in rtf file? i found an ancient answer How can I save the attributed string (text) into file (swift, cocoa)? I do not quite understand what exactly is required of me, maybe new different way exists somewhere?
Asked
Active
Viewed 1,070 times
5
-
1Please take a look at Apple's documentation on NSAttributedString. There is a function that converts a NSAttributedString to a RFT data stream. Once you have the data stream write it like any other file. – Bill Mar 17 '21 at 05:27
2 Answers
9
You can use NSAttributedString
's data(from:)
method to convert your attributed string into rtf data.
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)
}

Leo Dabus
- 229,809
- 59
- 489
- 571
0
Swift 4
do {
let attributedString = try NSAttributedString(url: fileURL, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
} catch {
print("\(error.localizedDescription)")
}

nimesh surani
- 177
- 1
- 13