2
votes

I have this code in a new playground

import Foundation

let blogsURL: NSURL = NSURL(fileURLWithPath: "/Users/Francis/Documents/Xcode_projects/KM registratie/blogs.json")
let data = NSData(contentsOfURL: blogsURL)

On the second line the playground tells me that it (correctly) initialised the URL referring to file:///Users/Francis/Documents/Xcode_projects/KM%20registratie/blogs.json and on the third line the playground tells me that data is nil

I already googled around but no question seems to be the exact same problem. I found this "NSData contentsOfURL constructor returns nil", but neither restarting Xcode nor restarting my entire computer fixes the problem.

2
Not sure about the %20, but it should probably be an escaped space instead of encoded : "/Users/Francis/Documents/Xcode_projects/KM\ registratie/blogs.json" - Wain
you only escape when you don't put parentheses around a path right? In that case there's no need to escape the space. But I tried it anyway, it gives a syntax error on the back slash - Fr4nc3sc0NL
I guess, the playground is in its own sandbox and cannot access files outside. - vadian
I already answered the question, thanks to @vadian, but I do wonder now if %20 is appropriate in a system path :p - Fr4nc3sc0NL
@Fr4nc3sc0NL any space character in an URL has to be percent escaped even in a file system URL - vadian

2 Answers

0
votes

playgrounds are sandboxed and it seems that there isn't an easy way to reach outside their "box". XML parsing in swift the title of this question is a bit misleading, the answer on it does answer this question

0
votes

It's answered here:

XML parsing in swift

The problem is that your URL isn't pointing where you think it is. You're trying to open a URL in a subdirectory in your sandbox, and it doesn't exist.

You'll need to open the package contents of your playground (right click on the playground and select "Show Package Contents", add a folder called "Resources", and copy your file directly there.

Then you can get the file from the main bundle:

let url: NSURL! = NSBundle.mainBundle().URLForResource("blogs", withExtension: "json")