Nizam Nizam -5 years ago 219
Swift Question

Full path of project

I want to open a text file in Swift and I managed to do it passing the full path as parameter:

let dados = String.stringWithContentsOfFile("/Users/aczuquim/Google Drive/Swift/Verdadeiro ou Falso/Verdadeiro ou Falso/Dados.txt", encoding: NSUTF8StringEncoding, error: nil)

Since, I added the file to the project, is there any way to use relative path?

When I use the relative path, a
is returned.


In the playground, the line bellow works fine:

let dados = String.stringWithContentsOfFile("/Users/aczuquim/Google Drive/Swift/Verdadeiro ou Falso/Verdadeiro ou Falso/dados.txt", encoding: NSUTF8StringEncoding, error: nil)

But not the following ones (

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("dados", ofType: "txt")

Answer Source

Bundle resource:

Swift 3.0

if let bundle = Bundle.main().urlForResource("Info", withExtension: "plist") {
    print("Path: \(bundle)")

Swift 2.0

let bundleURL = NSBundle.mainBundle()!.URLForResource("dados", withExtension: "txt")

If a nil is returned then the resource is not found and an error reported (note the exclamation mark after mainBundle). Check Build Phases - Copy Bundle Resources if the resource is being included.

App and Documents Folder

Get the documents folder from an array of [AnyObject]! which casts the first object to the NSURL type:

let docFolderURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
        println("DocumentFolderURL: \(docFolderURL)")

Then get the App folder, by stepping up to the parent folder and delete the last path component:

let appFolderURL = docFolderURL.URLByDeletingLastPathComponent
println("AppFolderURL: \(appFolderURL)")

Other directories may be accessed by using .URLByAppendingPathComponent(pathComponent: String?, isDirectory:Bool) etc.

Temporary Directory

var tempURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true).URLByDeletingLastPathComponent

Note that Apple now prefers the use of URLĀ“s to access folders and files and new methods use them exclusively. To use the path in older methods just call: tempURL.path

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download