Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 932
VYT Avatar asked Sep 08 '25 10:09

VYT


1 Answers

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
    {
    }
}
like image 89
VYT Avatar answered Sep 11 '25 05:09

VYT