Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a text file in the Resources directory using Swift 3 Playground?

I have a text file I created in the Resources directory of my Swift playground. I am trying to get the directory location of the "Resources" in the Playground during runtime, but it returns some other location that does not even exist.

import PlaygroundSupport
let dirLog = PlaygroundSupport.playgroundSharedDataDirectory

dirLog displays as:

file:///Users/ronaldo/Documents/Shared%20Playground%20Data/

It seems that PlaygroundSupport does not have the methods I need to get this directory location. I saw some mention in another SE question and they used NSBundle class to get the files in Resources. But I can not find ANY NSBundle object to be used in Swift 3.

like image 788
Ronaldo Nascimento Avatar asked Nov 07 '16 17:11

Ronaldo Nascimento


1 Answers

Each Playground has its own Resources folder, and the actual path is hidden.

In Swift 3, you can get the files in the Resources folder by using Bundle:

let url = Bundle.main.url(forResource: "file", withExtension: "txt")

The path of this Bundle URL contains the path to the current Resources folder.


You can also avoid using Bundle and drag & drop the file from the Resources folder to the Playground itself, creating a file literal.

For example, type let url = and drop the file, from the Resources folder, into the Playground just after the = sign.

like image 132
Eric Aya Avatar answered Nov 06 '22 22:11

Eric Aya