简体   繁体   中英

FileManager.createDirectory fails with NSCocoaErrorDomain Code: 518

I'm doing

    let tempDirectory = URL(string: "\(NSTemporaryDirectory())video/")!
    do {
        try FileManager.default.createDirectory(
            at: tempDirectory,
            withIntermediateDirectories: true)
    } catch { report(error) }

and that's often throwing an NSCocoaErrorDomain Code: 518.

Any idea of the reason? I thought that could because there's already something there, so I added

    var isDir: ObjCBool = false
    if FileManager.default.fileExists(
        atPath: tempDirectory.absoluteString,
        isDirectory: &isDir
    ) {
        if isDir.boolValue {
            print("Temp directory exists on launch")
        }
        else {
            print("Temp directory exists on launch and is a file")
        }
        return
    }

but that doesn't seem to catch anything

Your building of tempDirectory isn't correct. You want:

let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory()). appendingPathComponent("video")

The issue with your code is that you were not passing a value URL string to URL(string:) . Since you have a file path you need to use URL(fileURLWithPath:) . And build paths/URLs using the provided methods to ensure slashes and other parts are added correctly.

Print your value of tempDirectory from your original code and then print the new value from the code in my answer. Note the key difference.

Your URL will be something like:

/var/...

and it may be missing the slash before "video".

The correct file URL will be something like:

file:///var/...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM