Using NSFileManager and createDirectoryAtPath in Swift

I am trying to create a new folder, but I cannot figure out how to use createDirectoryAtPath correctly.

According to the documentation, this is the correct syntax:

NSFileManager.createDirectoryAtPath(_:withIntermediateDirectories:attributes:error:)

I tried this:

let destinationFolder: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let deliverablePath: NSURL = NSURL.fileURLWithPath("\(destinationFolder)/\(arrayOfProjectIDs[index])")!
NSFileManager.createDirectoryAtPath(deliverablePath, withIntermediateDirectories: false, attributes: nil, error: nil)

But it gives me an error

Optional argument 'withIntermediateDirectories' when invoked

I also tried many options, deleting options, etc., but I can't get it to work without errors. Any ideas?

+4
source share
4 answers

You forgot to add defaultManager()and convert NSURL to String.

You can try replacing

NSFileManager.createDirectoryAtPath(deliverablePath, withIntermediateDirectories: false, attributes: nil, error: nil)

with this (converting NSURL to string)

var deliverablePathString = deliverablePath.absoluteString

NSFileManager.defaultManager().createDirectoryAtPath(deliverablePathString, withIntermediateDirectories: false, attributes: nil, error: nil)

Hope this helps

+5
source

Swift 2.0 method:

do {
    var deliverablePathString = "/tmp/asdf"
    try NSFileManager.defaultManager().createDirectoryAtPath(deliverablePathString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    NSLog("\(error.localizedDescription)")
}
+10

createDirectoryAtPath String , URL. URL- createDirectoryForURL.

:

NSFileManager.defaultManager().createDirectoryAtPath("/tmp/fnord", withIntermediateDirectories: false, attributes: nil, error: nil)

+3

Based on seb code above. When I used this in my function, I had to add a common catch. This removed "Errors dropped from here are not processed because the closed catch error is not exhaustive."

do {
    var deliverablePathString = "/tmp/asdf"
    try NSFileManager.defaultManager().createDirectoryAtPath(deliverablePathString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    NSLog("\(error.localizedDescription)")
} catch {
    print("general error - \(error)", appendNewline: true)
}
+1
source

All Articles