Documents directory?

How do I get the documents directory in Swift?


I've done it a hundred times in Objective-C.


The expression I found for doing this in Swift is:

let documentsPath: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String


When I run my app and stop in the debugger and try to display this string, the debugger prints "<variable not available>".


If I ignore that and try to create a file anyway, the file handle comes back nil:


let filePath = "\(documentsPath)/data.bin"

let file: FileHandle? = FileHandle(forWritingAtPath: filePath)

I suggest you start using the FileManager method "url(for:in:appropriateFor:create:)" instead. URLs are always preferred, and it doesn't return a pesky array. There is also a FileHandle initializer that takes a URL instead of a path.


The main advantage of this is that both of these methods throw an error if they fail, so you will get an error description telling you what's wrong.

This works in Swift 4:

var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL


Is it what you are looking for ?

Documents directory?
 
 
Q