5

I'm using:

let dialog = NSOpenPanel()

to get a file URL.

I'm then reading in the contents of the text file with:

let content = try String( contentsOf: dialog.url)

This works!

I'm then trying to read in another text file in the same directory with a different extension:

let b = dialog.url?.deletingPathExtension()
// Add the new file extension
let c = b?.appendingPathExtension("TSN") 

let content2 = try String( contentsOf: c)

With this I get:

"The file “FLO5.TSN” couldn’t be opened because you don’t have permission to view it."

If I try and open the .tsn file with a URL from a NSOpenPanel() dialog result it works. I need to open several data files from this same directory with different extensions. Is there a way to do this?

Andrew
  • 521
  • 7
  • 18

2 Answers2

7

set off sandbox!!) Xcode 9 and later enables sandboxing by default, which severely limits interactions with the system.

Select your target, then Capabilities and set Downloads Folder to Read/Write:

enter image description here

matt
  • 515,959
  • 87
  • 875
  • 1,141
Sam
  • 79
  • 1
  • 4
2

In my case, solve it's startAccessingSecurityScopedResource

Example:

let selectedFile = try result.get() // get path to file

                do {
                    // get access to open file
                    if selectedFile.startAccessingSecurityScopedResource() {
                        let path = selectedFile.path
                        let data = NSData(contentsOfFile: path)
                        print(data) // array bytes
                        selectedFile.stopAccessingSecurityScopedResource()
                    }

                } catch {
                    // Couldn't read the file.
                    print(error.localizedDescription)
                }

Apple wiki about this feature https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso

antipups
  • 153
  • 3
  • 9