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?
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.
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.
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.
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.
We can use the Bundle.main
So, if you have a test.json in your playground like
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With