How can I write NSAttributedString in rtf file?

Viewed 599
2 Answers

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)")
}
Related