无法创建临时目录

Can't create temporary directory

我在使用 Swift 在 iOS 中创建临时目录时遇到问题 3. 我正在从 FileManager.temporaryDirectory 获取临时目录 URL,并尝试使用 FileManager.createDirectory 创建目录,但该目录似乎不存在,我无法在其中创建文件。我究竟做错了什么?

let fileManager = FileManager.default
let tempDir = fileManager.temporaryDirectory
let tempDirString = String( describing: tempDir )
print( "tempDir: \(tempDir)" )
print( "tempDirString: \(tempDirString)" )
if fileManager.fileExists(atPath: tempDirString ) {
    print( "tempDir exists" )
} else {
    print( "tempDir DOES NOT exist" )
    do {
        try fileManager.createDirectory( at: tempDir, withIntermediateDirectories: true, attributes: nil )
        print( "tempDir created" )
        if fileManager.fileExists(atPath: tempDirString ) {
            print( "tempDir exists" )
        } else {
            print( "tempDir STILL DOES NOT exist" )
        }
    } catch {
        print( "tempDir NOT created" )
    }
}

这会产生输出:

tempDir: file:///private/var/mobile/Containers/Data/Application/D28B9C5E-8289-4C1F-89D7-7E9EE162AC27/tmp/
tempDirString: file:///private/var/mobile/Containers/Data/Application/ D28B9C5E-8289-4C1F-89D7-7E9EE162AC27/tmp/
tempDir DOES NOT exist
tempDir created
tempDir STILL DOES NOT exist

您传递给 fileManager.fileExists(atPath: tempDirString )tempDirString 字符串包含一个字符串,但该字符串不是文件路径。它是用于人类可读目的的描述,而不是用于 machine-readable 目的。事实上,它甚至不是一个有效的 URL 字符串(注意其中的 space!)。

如果需要路径,请替换此行:

let tempDirString = String( describing: tempDir )

而是将 NSURL 的 path 函数的结果分配给 tempDirString 以获取字符串形式的路径:

let tempDirString = tempDir.path

参见:https://developer.apple.com/reference/foundation/nsurl/1408809-path