8

Can some body help me why the below code is not working.. I am testing it in Xcode.1 Playground

let url:NSURL! = NSURL(fileURLWithPath:"file:///Users/sss/Documents/app.xml")

var xml = NSXMLParser(contentsOfURL: url)

xml?.parse()
Nate Cook
  • 92,417
  • 32
  • 217
  • 178

1 Answers1

20

Playgrounds are sandboxed, so you won't be able to just grab files from anywhere in your user folder. Here's how to add that file to your playground to make it accessible:

  1. Find your ".playground" file in the Finder
  2. Right click and choose "Show Package Contents"
  3. You should see "timeline.xctimeline", "contents.xcplayground", and "section-1.swift"
  4. Make a new folder called "Resources"
  5. Copy "app.xml" into that new folder

Now your file will be available inside the sandbox. You can retrieve it from the bundle and load it into the NSXMLParser like this:

let url: NSURL! = NSBundle.mainBundle().URLForResource("app", withExtension: "xml")
var xml = NSXMLParser(contentsOfURL: url)
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • Hi Nate Cook thank you very much for your great help. Now i understood that playground is a sandboxed envirornment. But can you tell me why the same 3 lines of code is not working on Mac OS X application. Actually i have a requirement in my mac application where i have to parse xml file selected by the user from the NSOpenPanel – appdevelopersspotlight Nov 04 '14 at 06:46
  • Missed your follow-up, sorry! If you're still having this trouble, can you post a new question? I'm not totally familiar with `NSOpenPanel` and OS X sandboxing. – Nate Cook Nov 17 '14 at 16:29
  • If you have the playground file open when making these changes, remember to close and reopen it before trying to access files in the Resources folder. – n.Drake Jun 29 '15 at 13:05