Swift 2.0 works in Xcode, but not in Playground

I am learning Swift and was upset trying to figure out how I cannot upload files. It turns out that the code works in Xcode, but does not work on the playground. What is the reason for this?

Here is the code:

func testFileLoad(){ let myFilePath: String = "/Users/clay/Desktop/test.txt" let t: Bool = NSFileManager.defaultManager().fileExistsAtPath(myFilePath) print(t) let s: String = try! String(contentsOfFile: myFilePath, encoding: NSUTF8StringEncoding) print(s) do { let p: String = try String(contentsOfFile: myFilePath, encoding: NSUTF8StringEncoding) print(p) } catch { print("nope") } } 

Running in a test module in Xcode, it works correctly and prints what I hope for the console.

 Test Suite 'Selected tests' started at 2015-08-05 14:24:15.977 Test Suite 'swiftgraphTests' started at 2015-08-05 14:24:15.978 Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' started. true this is a test this is a test Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' passed (0.001 seconds). Test Suite 'swiftgraphTests' passed at 2015-08-05 14:24:15.979. Executed 1 test, with 0 failures (0 unexpected) in 0.001 (0.001) seconds Test Suite 'Selected tests' passed at 2015-08-05 14:24:15.979. Executed 1 test, with 0 failures (0 unexpected) in 0.001 (0.002) seconds 

On the playground, I get the following:

enter image description here

What am I doing wrong here? Am I using the playground incorrectly?

+6
source share
2 answers

If you go to the menu

View → Debug Area → Show Debug Area

you will see a complete error: "you do not have access rights to the file system from the playground".

The workaround is to include the file in the Playground using its Project Navigator.

Go to menu

View → Navigators → Show Project Navigator

then drag your file into the Resources folder.

Then use the NSBundle to get the path.

 func testFileLoad() { // get the file path for the file from the Playground Resources folder guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "txt") else { print("Oops, the file is not in the Playground") return } // keeping the examples from your question let s: String = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding) print(s) do { let p: String = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding) print(p) } catch { print("nope") } } testFileLoad() 

* In fact, you only have access to the /var/ folder containing your shared data on the Playground, and Playground just offers a shortcut. This folder in the Playground navigator actually represents the /var/ folder and is unique for each playground. You can see its address using NSBundle:

 NSBundle.mainBundle().resourcePath 
+7
source

Perhaps the problem is resolved. You probably have a set of privileges in your Xcode project that are not available on the playground.

+2
source

All Articles