简体   繁体   中英

Can't write string to file inside of NSSavePanel “ok” function

For some reason, I can only write a string to a file outside of NSSavePanel 's ok function. I need to write it as soon as the user says "OK, I do want to save that".

Here is my code:

//An IBAction that connects to the "Save" menu item.
@IBAction func SaveButton(_ sender: Any) {
    os_log("Save button pressed.")
    //Declares savePanel to be equal to NSSavePanel opens the save panel in a seperate window.
    let savePanel = NSSavePanel()
    savePanel.runModal()

    let textEntryController = EntryViewController()


    //Sets a placeholder of the text we're going to write.
    func ok(_ sender: Any?){

        let entryPath = savePanel.url
        let entryFieldContents = textEntryController.entryTextField!;
        let entryText = (entryFieldContents.textStorage as NSAttributedString?)?.string
        let entryContent = entryText
        do {
            try entryContent?.write(to: entryPath!, atomically: true, encoding: String.Encoding.utf8)
        } catch {
            // failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
        }

    }

Instead of using runModal() you should use the more modern closure syntax:

let savePanel = NSSavePanel()
savePanel.begin { (response) in
    if response == .OK {
        // write it here
    }
}

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