如何在iOS swift上下载多个文件并保存在设备上

How to Download multiple files and save on device on iOS swift

提问人:Juno 提问时间:6/7/2023 更新时间:6/7/2023 访问量:142

问:

我想在循环中调用“loadFileAsync”方法并将文件保存在本地,但我总是收到错误,因为尽管该位置存在文件,但文件不存在。请帮忙。这是我的代码。不明白我做错了什么?谢谢!

if let screens = ServerDrivenUIComponent.sharedInstance.appGenericUIModel?.screens{
            for aScreen in screens{
                let clientUrl = URL(string:"File location url")
                    FileDownloader.loadFileAsync(folder: self.selectedClient, url: clientUrl!) { destinationPath, error in
                        if destinationPath != nil{
                            
                        }
                    }
                }
            }
        }

我想从此方法取回目标网址,因此添加了@escaping

static func loadFileAsync(folder:String, url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        var filePath = URL(string: "")
        if let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        filePath = documentsUrl

        let destinationUrl = filePath!.appendingPathComponent(url.lastPathComponent)
if FileManager().fileExists(atPath: destinationUrl.path){
                print("File already exists [\(destinationUrl.path)]")
                do{
                    try FileManager.default.removeItem(at: destinationUrl)
                }
                catch{
                }
            }
            
            let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
                if let tempLocalUrl = tempLocalUrl, error == nil {
                    // Success
                    if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                        if statusCode == 200{
                            do {
                                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationUrl)
                                completion(destinationUrl.path, nil)
                            } catch (let writeError) {
                                print("Error creating a file \(destinationUrl) : \(writeError)")
                                completion(nil, writeError)
                            }
                        }
                        else{
                            print("File is not present at \(url.absoluteString)")
                            completion(nil, error)
                        }
                    }
                }
                else {
                }
            }
            task.resume()
}
iOS Swift 异步 并发

评论

0赞 Mahmoud Eissa 6/7/2023
嗨,@Juno,如果状态代码 != 200,则从上面的代码中,您会收到此错误“文件不存在”,您能否分享一个可下载链接的示例来检查?
0赞 Rob 6/9/2023
一堆不相关的观察结果:gist.github.com/robertmryan/9ec86d0bd6d8468aeb9d5affb4a36cd1

答: 暂无答案