ios - 文件快速下载后出现奇怪的错误
问题描述
我正在尝试从远程服务器下载文件。文件可用,下载也完成。文件名我从collectionview与文件一起发送到这个函数,所以名称是正确的。但是我在文件保存方面遇到了一些问题。这是我的文件加载方式:
func testLoad(attachName:String) {
let documentsUrl:URL = (FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first as URL?)!
let destinationFileUrl = documentsUrl.appendingPathComponent(attachName)
var request = URLRequest(url: Pathes.init(endpoint: "message/\(mModel?.id ?? -1)/attachment/\(attachName)?type=\(mType ?? -1)").resourseUrl)
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer " + UserDefaults.standard.string(forKey: "access_token")!, forHTTPHeaderField: "Authorization")
let task = URLSession(configuration: URLSessionConfiguration.default).downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
print("\(tempLocalUrl) ---> \(destinationFileUrl)")
if ((response as? HTTPURLResponse)?.statusCode) != nil {
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
}
}
task.resume()
}
在下面你可以看到我的错误:
Error creating a file file:///Users/angor/Library/Developer/CoreSimulator/Devices/B83E640A-8EC4-475A-B272-5D884B611A8B/data/Containers/Data/Application/3DE475CE-B2B3-4971-9382-1F272160B1A4/Downloads/paolo-nicolello-dqy5wtCdS4U-unsplash.jpg : Error Domain=NSCocoaErrorDomain Code=516 "“CFNetworkDownload_mw7QwY.tmp” couldn’t be copied to “Downloads” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/Users/angor/Library/Developer/CoreSimulator/Devices/B83E640A-8EC4-475A-B272-5D884B611A8B/data/Containers/Data/Application/3DE475CE-B2B3-4971-9382-1F272160B1A4/tmp/CFNetworkDownload_mw7QwY.tmp, NSUserStringVariant=(
Copy
), NSDestinationFilePath=/Users/angor/Library/Developer/CoreSimulator/Devices/B83E640A-8EC4-475A-B272-5D884B611A8B/data/Containers/Data/Application/3DE475CE-B2B3-4971-9382-1F272160B1A4/Downloads/paolo-nicolello-dqy5wtCdS4U-unsplash.jpg, NSFilePath=/Users/angor/Library/Developer/CoreSimulator/Devices/B83E640A-8EC4-475A-B272-5D884B611A8B/data/Containers/Data/Application/3DE475CE-B2B3-4971-9382-1F272160B1A4/tmp/CFNetworkDownload_mw7QwY.tmp, NSUnderlyingError=0x60000232c150 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}
我不明白为什么会这样。该错误表明我的文件存在,但我的Downloads
目录中没有看到任何新文件。我认为问题与必须复制到的临时文件有关Downloads
。我在这里找到了这种文件下载方式,也许我做错了?
解决方案
我已经设法找出问题出在哪里:) 我添加了从tmp
文件夹中删除临时创建的文件,并将所有文件下载代码移动到扩展名:
extension UIViewController:URLSessionDownloadDelegate{
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let url = downloadTask.originalRequest?.url else { return }
let documentsPath = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)
try? FileManager.default.removeItem(at: destinationURL)
do {
try FileManager.default.copyItem(at: location, to: destinationURL)
} catch let error {
print("Copy Error: \(error.localizedDescription)")
}
}
}
也许它会帮助除我以外的其他人:)
推荐阅读
- python - pandas 如何逐行迭代地计算一个类别的实例并在另一个类别出现时重置它们?
- python - 在单独的行中创建提交、作者、时间戳、文件日志的列
- scala - CanBuildFrom 和类型上限参数
- ocaml - OCaml 递归函数:子列表元素乘以它们在列表中的位置,然后求和
- sql - SQL 两个 JOINS 同一张表不同的值
- anylogic - ResourceTaskStart 独立
- powerbi - 将 Snowflake 连接到 Power BI 期间发生错误
- flutter - Dart - 重用 Flutter 小部件有时包含错误的数据
- azure-devops - 有条件地复制 Azure Pipeline 中的文件夹
- javascript - 如何从 JS 中的 HTML 标签元素中仅获取文本节点的内容(不是嵌套标签)?