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?
How can I write NSAttributedString in rtf file?
Please 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. –
Ferrotype
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)
}
Swift 4
do {
let attributedString = try NSAttributedString(url: fileURL, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
} catch {
print("\(error.localizedDescription)")
}
© 2022 - 2024 — McMap. All rights reserved.