提问人:Juno 提问时间:6/7/2023 更新时间:6/7/2023 访问量:142
如何在iOS swift上下载多个文件并保存在设备上
How to Download multiple files and save on device on iOS swift
问:
我想在循环中调用“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()
}
答: 暂无答案
评论