2

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.

Community
  • 1
  • 1
Fr4nc3sc0NL
  • 555
  • 1
  • 6
  • 22
  • 1
    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 Nov 13 '15 at 17:28
  • 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 Nov 13 '15 at 17:37
  • 3
    I guess, the playground is in its own sandbox and cannot access files outside. – vadian Nov 13 '15 at 17:37
  • maybe need 2 slashes so you aren't escaping in the `String` but you are in the path creation, though it may be that %20 is appropriate – Wain Nov 13 '15 at 17:39
  • 1
    I already answered the question, thanks to @vadian, but I do wonder now if %20 is appropriate in a system path :p – Fr4nc3sc0NL Nov 13 '15 at 17:47
  • 1
    @Fr4nc3sc0NL any space character in an URL has to be percent escaped even in a file system URL – vadian Nov 13 '15 at 23:16

2 Answers2

0

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

Community
  • 1
  • 1
Fr4nc3sc0NL
  • 555
  • 1
  • 6
  • 22
0

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")
Community
  • 1
  • 1
The Cappy
  • 623
  • 4
  • 8