Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an iOS application's “~/Library” path reliably in Swift

Tags:

ios

swift

I want to get the directory where I can create files and write logs to files in my swift app for iOS devices. I read here, https://stackoverflow.com/a/3763050/919280, that using Objective-C, there is a solution. I tried writing it in swift like this:

var appDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, true)

But, NSLibraryDirectory and NSUserDomainMask do not seem to be present in Swift. What is the way to do this is Swift?

like image 306
Rishi Avatar asked Sep 02 '14 11:09

Rishi


Video Answer


1 Answers

Solution:

var appDir = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)

Explanation:
You can click on method and see it's declaration.

func NSSearchPathForDirectoriesInDomains(directory: NSSearchPathDirectory, domainMask: NSSearchPathDomainMask, expandTilde: Bool) -> [AnyObject]!

As you can see it takes NSSearchPathDirectory enum
and NSSearchPathDomainMask struct.

In swift, when you use enums, you don't need to specify enum type, you can use case values itself .LibraryDirectory instead of NSSearchPathDirectory.LibraryDirectory

Swift 5

Enums are lower-case now:

.libraryDirectory

.userDomainMask
like image 94
Kostiantyn Koval Avatar answered Sep 28 '22 00:09

Kostiantyn Koval