下载文件后出现奇怪的错误 swift

Strange error after file downloading swift

我正在尝试从远程服务器下载文件。文件可用,下载也已完成。文件名我用文件从 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 的临时文件有关。我发现了这种文件下载方式here可能我做错了?

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

也许它会对我以外的其他人有所帮助:)