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

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


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 bundlelet filePath = Bundle.main.path(forResource:"test", ofType: "json")// get the contentDatalet contentData = FileManager.default.contents(atPath: filePath!)// get the stringlet content = String(data:contentData!, encoding:String.Encoding.utf8)// printprint("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.jsoncontent: {    "name":"jc",    "company": {        "name": "Netscape",        "city": "Mountain View"    }}


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

// get the file path for the file "test.json" in the playground bundlelet filePath = Bundle.main.path(forResource: "test", ofType: "json")// get the contentDatalet contentData = FileManager.default.contents(atPath: filePath!)// get the stringlet content = String(data: contentData!, encoding: .utf8)// printprint("filepath: \(filePath!)")if let c = content {    print("content: \n\(c)")}


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)