Search code examples
swift3swift-playground

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.


Solution

  • 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.