Using NSFileManager and createDirectoryAtPath in Swift

微笑、不失礼 提交于 2019-12-01 17:30:57

问题


I'm trying to create a new folder, but I can't 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 this gives me the error

Extra argument 'withIntermediateDirectories' in call

I've also tried a lot of variations, removing parameters and so on, but I can't get it to run without an error. Any ideas?


回答1:


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

You can try replacing

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

with this (converting your NSURL to String)

var deliverablePathString = deliverablePath.absoluteString

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

Hope this helps




回答2:


The Swift 2.0 way:

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



回答3:


createDirectoryAtPath expects a String for the first parameter, not a URL. Try passing your path directly or use the URL-friendly variant createDirectoryForURL.

Here is an example:

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




回答4:


Based on seb's code above. When I used this in my function I had to add a generic catch too. This removed the "Errors thrown from here are not handled because the enclosing catch is not exhaustive" error.

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)
}


来源:https://stackoverflow.com/questions/29337187/using-nsfilemanager-and-createdirectoryatpath-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!