12

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?

Community
  • 1
  • 1
Rishi
  • 1,987
  • 6
  • 32
  • 49

1 Answers1

19

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
James Toomey
  • 5,635
  • 3
  • 37
  • 41
Kostiantyn Koval
  • 8,407
  • 1
  • 45
  • 58
  • 1
    Where is the conversion of NSLibraryDirectory to .LibraryDirectory (or similar) documented? I want to understand why one option begins with , and the other needs a namespace – mmmmmm Sep 02 '14 at 12:17
  • 1
    see my edit's to answer. Xcode generate Swift header for all classes. if you click on NSSearchPathForDirectoriesInDomains. it will show you Foundation->NSPatchUtilities file with Swift declarations – Kostiantyn Koval Sep 02 '14 at 12:20
  • There is an Xcode bug that sometimes it can't show Swift classes when you click one method and want to see documentation. (It's because Swift is still in beta). Then try to restart Xcode, it helps sometimes – Kostiantyn Koval Sep 02 '14 at 12:23
  • The second argument can also be shortened to `.UserDomainMask` – Martin R Sep 02 '14 at 13:04
  • @KostiantynKoval is there a difference between `NSSearchPathForDirectoriesInDomains` and `FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)` ? – Michael Mar 01 '21 at 23:20