无法创建临时目录

时间:2017-02-10 01:49:49

标签: ios swift3 temporary-files

我在使用Swift 3在iOS中创建临时目录时遇到问题。我从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

1 个答案:

答案 0 :(得分:3)

您传递给tempDirString的{​​{1}}字符串包含一个字符串,但该字符串不是文件路径。它是用于人类可读目的的描述,不是出于机器可读目的。实际上,它甚至不是有效的URL字符串(请注意其中的空格!)。

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

fileManager.fileExists(atPath: tempDirString )

而是分配给let tempDirString = String( describing: tempDir ) NSURL的tempDirString函数的结果,以便将路径作为字符串:

path

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