简体   繁体   中英

How can I save the attributed string (text) into file (swift, cocoa)?

I have NSTextView and I can have text as nsattributedstring. I can save text into .txt file using NSSavePanel, as plain text, but not as formatted text.

@IBAction func saveDNA(sender: AnyObject)
{
    let saveDNAtoFile:  NSSavePanel = NSSavePanel()
    saveDNAtoFile.canSelectHiddenExtension = true
    saveDNAtoFile.runModal()

    do
    {
        let exportedFileURL = saveDNAtoFile.URL
        let textDNA = self.inputDnaFromUser.string

        if exportedFileURL != nil
        {
            try textDNA!.writeToURL(exportedFileURL!, atomically: false, encoding: NSUTF8StringEncoding)
        }
    } catch
    {
    }
}

How can I save the attributedstring (text) into file using NSSavePanel, to be able later to open this file to have all made before formatting in the text? What I should change in the code above, if I can use NSSavePanel for this ?

One day out ... Ok, I have figured out the code for Swift 2 (note this - options: NSFileWrapperWritingOptions.Atomic). Below. I am sure it will save time for beginners like me, more time to write necessary and more interesting algorithms, than this standard functionality.

@IBAction func saveDNA(sender: AnyObject)
{
    let saveDNAtoFile:  NSSavePanel = NSSavePanel()
    saveDNAtoFile.canSelectHiddenExtension = true
    saveDNAtoFile.runModal()

    do
    {
        let exportedFileURL = saveDNAtoFile.URL

        let textDNA = inputDnaFromUser.textStorage

        if exportedFileURL != nil
        {
            let range = NSRange(0..<textDNA!.length)

            let textTSave = try textDNA!.fileWrapperFromRange(range, documentAttributes: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType])
            try textTSave.writeToURL(exportedFileURL!, options: NSFileWrapperWritingOptions.Atomic, originalContentsURL: nil)

        }
    } catch
    {
    }
}

AppKit adds many methods to NSAttributedString . They are documented in the NSAttributedString AppKit Additions Reference . Of interest to you are these, for converting to various external formats:

  • dataFromRange(_:documentAttributes:)
  • fileWrapperFromRange(_:documentAttributes:)
  • docFormatFromRange(_:documentAttributes:)
  • RTFFromRange(_:documentAttributes:)
  • RTFDFromRange(_:documentAttributes:)
  • RTFDFileWrapperFromRange(_:documentAttributes:)

and these, for converting those external formats back to instances of NSAttributedString :

  • init(data:options:documentAttributes:)
  • init(docFormat:documentAttributes:)
  • init(RTF:documentAttributes:)
  • init(RTFD:documentAttributes:)
  • init(RTFDFileWrapper:documentAttributes:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM