How can I write NSAttributedString in rtf file?
Asked Answered
I

2

5

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?

Indubitability answered 17/3, 2021 at 5:17 Comment(1)
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
S
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)
}
Stitt answered 17/3, 2021 at 8:11 Comment(0)
Y
0

Swift 4

do {
    let attributedString = try NSAttributedString(url: fileURL, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
} catch {
    print("\(error.localizedDescription)")
}
Yelp answered 17/3, 2021 at 5:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.