4

I am having trouble reading a file within a command line tool project in Xcode 11.6.

Steps:

Create a new command line tool project using the template in the mac os section.

In main.swift:

import Foundation let fileURL = URL( fileURLWithPath: "/Users/ausom4/Desktop/myTest.txt" ) var rawDataString: String var errorString: String? do { rawDataString = try String( contentsOf: fileURL, encoding: .utf8 ) print(rawDataString) } catch let error as NSError { errorString = error.description rawDataString = "" print(rawDataString) } 

This will build successfully in Xcode however will always print a null string in the console.

However if I go to the location of my product in terminal and run the build I get the contents of the file.

I do not have sandboxing enabled. Sandboxing is also not enabled by default in this xcode template. I have also given xcode full disk access.

I can run this code in a playground.

What could be the issue here?

2
  • The first step to debug the problem would be to print(error) ... Commented Aug 23, 2020 at 19:44
  • I get the following error: Error Domain=NSCocoaErrorDomain Code=257 "The file “myTest.txt” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/Users/ausom4/Desktop/myTest.txt, NSUnderlyingError=0x1005425e0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}} I tried giving my file chmod 777 permissions, but the same error is returned Commented Aug 23, 2020 at 19:47

1 Answer 1

2

It is not sandbox - it is macOS Security & Privacy system.

On first launch you had to get alert asking something like “TestFileReading” would like to access files in your Desktop folder. so you grand access for this application.

If you did not grant access then (or for some reason macOS forgot to ask that) there is possibility to grant access manually in System Preferences at any time:

demo

With all this passed your code snippet works as expected - tested with Xcode 12 / macOS 10.15.6

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately I never get a prompt from xcode when running the project for permissions to the desktop. I cannot add new apps to the flles and folders menu only remove them after unlocking. I am using 11.0 beta.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.