swiftmacos

File couldn’t be opened because you don’t have permission to view it error


I have Googled and poked around Stack Overflow and can't seem to find a solution for this. I have:

let fileURL = URL( string: "file:///Users/me/file.txt" )    
var rawDataString: String 
var errorString: String?

do {
    rawDataString = try String( contentsOf: fileURL!, encoding: String.Encoding.utf8 )
} catch let error as NSError {
    errorString = error.description
    print( errorString! )
    return
}

and it's erroring out with

Error Domain=NSCocoaErrorDomain Code=257 "The file “file.txt” couldn’t be opened because you don’t have permission to view it."

Permissions are read for all users:

$ ls -al file.txt
-rw-r--r--@ 1 me  staff  348306 Dec 13  2016 file.txt

Any ideas would be most welcome.


Solution

  • Anyone coming across this thread, @LeoDabus pointed me to where to turn off sandbox, which worked:

    enter image description here

    He also cleaned up my code a bit:

    let fileURL = URL( fileURLWithPath: "/Users/me/file.txt" )    
    var rawDataString: String
    var errorString: String?
    
    do {
        rawDataString = try String( contentsOf: fileURL, encoding: .utf8 )
    } catch let error as NSError {
        errorString = error.description
        rawDataString = ""
        return
    }