21

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?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Jeremy Chone
  • 3,079
  • 1
  • 27
  • 28

6 Answers6

41

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"
    }
}
Axel Guilmin
  • 11,454
  • 9
  • 54
  • 64
Jeremy Chone
  • 3,079
  • 1
  • 27
  • 28
  • Here is good to mention. To get the resources the bes way is to create the playground inside a **WorkSpace**. I will appear by default and in the correct spot. – jasmo2 Jul 08 '16 at 16:56
13

Jeremy Chone's answer, updated for Swift 3, Xcode 8:

// 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: .utf8)


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

if let c = content {
    print("content: \n\(c)")
}
Community
  • 1
  • 1
leanne
  • 7,940
  • 48
  • 77
  • filePath should be safely used. Please check if the filePath is not nil, for example using let. The same should be done with contentData. The code should be written so it can handle these problematic cases. – Heitara Mar 23 '17 at 22:14
7

You can use String directly with a URL. Example in Swift 3:

let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let text = String(contentsOf: url)
Damiaan Dufaux
  • 4,427
  • 1
  • 22
  • 33
5

Swift 5

It is possible to get to files in your Resources folder by the bundle in a Playground.

import UIKit

Here are two ways to get the JSON data.

Path:

    guard let path = Bundle.main.path(forResource:"test", ofType: "json"),
    let data = FileManager.default.contents(atPath: path) else {
        fatalError("Can not get json data")
    }

URL:

    guard let url = Bundle.main.url(forResource:"test", withExtension: "json") else {
            fatalError("Can not get json file")
    }
    if let data = try? Data(contentsOf: url) {
        // do something with data
    }
skymook
  • 3,401
  • 35
  • 39
2

Another short way (Swift 3):

let filePath = Bundle.main.path(forResource: "test", ofType: "json")
let content: String = String(contentsOfFile: filePath!, encoding: .utf8)
Yoav Aharoni
  • 2,672
  • 13
  • 18
1

Added try for swift3.1:

let url = Bundle.main.url(forResource: "test", withExtension: "json")!
// let text = String(contentsOf: url)
do {
    let text = try String(contentsOf: url)
    print("text: \n\(text)")
}
catch _ {
    // Error handling
}

// --------------------------------------------------------------------
let filePath2 = Bundle.main.path(forResource: "test", ofType: "json")
do {
    let content2: String = try String(contentsOfFile: filePath2!, encoding: .utf8)
    print("content2: \n\(content2)")

}
catch _ {
    // Error handling
}
  • It's very bad practice to ignore the errors in the catch block. You shouldn't use the `_` operator: just have `catch` and it will properly generate the `error` variable in the block. – Eric Aya Aug 04 '17 at 11:05