Using NSFileManager and createDirectoryAtPath in Swift

前端 未结 4 1410
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 02:04

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:

相关标签:
4条回答
  • 2021-01-19 02:50

    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)
    }
    
    0 讨论(0)
  • 2021-01-19 02:54

    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)")
    }
    
    0 讨论(0)
  • 2021-01-19 03:09

    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)

    0 讨论(0)
  • 2021-01-19 03:11

    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

    0 讨论(0)
提交回复
热议问题