繁体   English   中英

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

[英]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临时文件有关。 我在这里找到了这种文件下载方式,也许我做错了?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM