How to read a playground text resource files with Swift 2 and Xcode 7

Jeremy Chone picture Jeremy Chone · Jun 20, 2015 · Viewed 15.4k times · Source

Xcode 7 Playgrounds now supports loading files from the nested Resources directory.

I can get SKScene(fileNamed: "GameScene") when I have a GameScene.sks in my Resources or NSImage(named:"GameScene.png") if I have a GameScene.png in your Resources.

But how can I read a regular text file from the Playground Resources directory as well?

Answer

Jeremy Chone picture Jeremy Chone · Jun 20, 2015

We can use the Bundle.main

So, if you have a test.json in your playground like

enter image description here

You can access it and print its content like that:

// get the file path for the file "test.json" in the playground bundle
let filePath = Bundle.main.path(forResource:"test", ofType: "json")

// get the contentData
let contentData = FileManager.default.contents(atPath: filePath!)

// get the string
let content = String(data:contentData!, encoding:String.Encoding.utf8)

// print
print("filepath: \(filePath!)")

if let c = content {
    print("content: \n\(c)")
}

Will print

filepath: /var/folders/dm/zg6yp6yj7f58khhtmt8ttfq00000gn/T/com.apple.dt.Xcode.pg/applications/Json-7800-6.app/Contents/Resources/test.json
content: 
{
    "name":"jc",
    "company": {
        "name": "Netscape",
        "city": "Mountain View"
    }
}