2
votes

I'm trying to save a file in macOS using Swift. I have the following settings in my app:

In the info.plist I have this key set with a message I need access to the desktop:

Privacy - AppleEvents Sending Usage Description 

Though I never see the app make this request.

In my sandbox I have read/write set for User Selected File

enter image description here

I use NSOpenPanel to let the user select a file. The app then programmatically makes changes to the file selected. I display the changes in a textview. I then provide the option for the user to save the changes. This is done with a NSSavePanel and this code:

if let thisFileURL = currentFileURL  {
                
   guard let window = view.window else { return }
   let panel = NSSavePanel()
                
   panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser
   panel.nameFieldStringValue = thisFileURL.lastPathComponent
   panel.title                   = "Saving changes...";
   panel.showsResizeIndicator    = true;
   panel.showsHiddenFiles        = false;
   panel.canCreateDirectories    = true;
   panel.allowedFileTypes        = ["html"]
                
   panel.beginSheetModal(for: window) { (result) in
                    
   if (panel.runModal() == NSApplication.ModalResponse.OK), let saveFileURL = panel.url, let strToSave = self.strCleanContents  {
                        
          do {
             try strToSave.write(to: saveFileURL, atomically: true, encoding: .utf8)
          } catch {
             self.myAppManager.displayInfoAlert("Unmable to save file:\n\(error.localizedDescription)", self, [], false, response: {(bResponse:Bool) in })
          }
     }
}
                
                

currentFileURL is the URL to the file the user initially selected. strCleanContents is the edited string from the file the user selected.

When I test this no error is thrown. But nothing happens either. The SavePanel opens, I can navigate to a location, if I select the same location where the original file was located it ask if I want to overwrite the file. Clicking save though does nothing, the panel just sits there. I can't cancel the process, it doesn't close, the file is not written.

1
Call either beginSheetModal or runModal, not both.Willeke
Thanks, make this an answer so I can give you a bump!PruitIgoe

1 Answers

1
votes

beginSheetModal and runModal both display the Save Panel. Call either beginSheetModal to display the panel as a sheet or runModal to display the panel as a window.