Swift:构建应用程序时会删除文档文件



我有一个奇怪的问题,每次我构建应用程序时,文档目录中下载的文件都会被删除,所以我必须再次下载。只有当我构建应用程序时才会发生这种情况,当应用程序被杀死并再次打开时,我不会删除文件。

你碰巧知道为什么?

这是我下载文件的代码

DispatchQueue.main.async {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url: url)
let downloadTask = session.downloadTask(with: request) { tempLocalUrl, _, error in
if let tempLocalUrl = tempLocalUrl, error == nil {
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let documentName = "documentName" + "." + url.pathExtension
let destinationURL = documentsPath.appendingPathComponent(documentName)
if !FileManager.default.fileExists(atPath: destinationURL.path) {
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationURL)
} catch {
return
}
}
}
}
downloadTask.resume()
}

下载完成后检查现有文件。这将始终下载文件;如果目的地已经存在,它就不会复制文件。

正确的代码如下:

if !FileManager.default.fileExists(atPath: destinationURL.path) {
// Download the file
}

当然,您需要在下载之前决定文件名。

最新更新