Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 899
Jeremy Chone Avatar asked Jun 20 '15 18:06

Jeremy Chone


People also ask

How do I open a Swift playground file?

playground file. Open Utility inspector, In the playground press opt-cmd-1 to open the File Inspector. You should see the playground on the right. If you don't have it selected, press cmd-1 to open the Project Navigator and click on the playground file.

How do I read a text file in Swift?

To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.

What is the difference between Swift playground and Xcode?

Xcode and Swift are both software development products developed by Apple. Swift is a programming language used to create apps for iOS, macOS, tvOS, and watchOS. Xcode is an Integrated Development Environment (IDE) that comes with a set of tools that helps you build Apple-related apps.

How do I open Swift playground on Mac?

In the Swift Playgrounds app on your Mac, click Run My Code (or use the Touch Bar). If there are instructions on the right side of the screen, they slide down when you click Run My Code, so you can watch your code run in the live view. When you click Stop, the instructions slide back up.


Video Answer


1 Answers

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"
    }
}
like image 185
Jeremy Chone Avatar answered Oct 03 '22 20:10

Jeremy Chone