Swift:文件存在但无法删除,因为它不存在

时间:2016-06-24 09:16:19

标签: swift file nsfilemanager nsdocumentdirectory nserror

我正在尝试从Documents目录中删除文件。 fileManager.fileExists(atPath: dataUrl.path!)返回true,这意味着该文件存在,但尝试删除它会引发错误,显示No such file or directory

我的代码:

let directoryUrl = FileManager.default().urlsForDirectory(.documentDirectory, inDomains: .userDomainMask).first!
let pathComponent = "data.zip"

let dataUrl =  try! directoryUrl.appendingPathComponent(pathComponent)

let fileManager = FileManager.default()

do {
    do {
        let filelist = try fileManager.contentsOfDirectory(atPath: directoryUrl.path!)

        for filename in filelist {
            print(filename)
        }
    } catch {
        print(error)
    }

    if fileManager.fileExists(atPath: dataUrl!) {
        print("File exists")
        try fileManager.removeItem(atPath: dataUrl.path)
        print("Deleted existing data")
    } else {
        print("File does not exist")
    }
} catch {
    print("Could not delete data: \(error)")
}

我的控制台输出:

data.zip // File exists when trying to print it
File exists
Could not delete timetables: Error Domain=NSCocoaErrorDomain Code=4 "data.zip") couldn’t be removed." UserInfo={NSFilePath=Optional("/var/mobile/Containers/Data/Application/4CA64C91-219E-49DE-9039-6BA71640A570/Documents/data.zip"), NSUserStringVariant=(
    Remove
), NSUnderlyingError=0x17024bee0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

0 个答案:

没有答案