首页 > 解决方案 > 文件快速下载后出现奇怪的错误

问题描述

我正在尝试从远程服务器下载文件。文件可用,下载也完成。文件名我从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我在这里找到了这种文件下载方式,也许我做错了?

标签: iosswiftdownload-manager

解决方案


我已经设法找出问题出在哪里:) 我添加了从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)")
        }
    }
}

也许它会帮助除我以外的其他人:)


推荐阅读