gpt4 book ai didi

ios - 使用 urlsessiondownloadtask 从 url 下载文件后,文件无法打开

转载 作者:行者123 更新时间:2023-11-29 05:31:07 25 4
gpt4 key购买 nike

当我尝试从 url 下载文件时,文件会被下载并存储在文件夹中。但是当我尝试打开该文件时。该文件似乎已损坏,我无法打开该 pdf 文件。

我已经使用下面提到的代码尝试了所有可能性。但它们都不起作用。任何解决方案提前致谢。

static func downloadFileFromUrl(urlString:String, fileName:String,viewController : UIViewController) {

// Create destination URL
if let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first{
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
//Create URL to the source file you want to download
let fileURL = URL(string: urlString)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success

try? FileManager.default.removeItem(at: destinationFileUrl)
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
do {
//Show UIActivityViewController to save the downloaded file
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for indexx in 0..<contents.count {
if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
viewController.present(activityViewController, animated: true, completion: nil)
}
}
}
catch (let err) {
UIApplication.shared.keyWindow?.makeToast(message: err.localizedDescription)
}
} catch (let writeError) {
DispatchQueue.main.async(execute: {
UIApplication.shared.keyWindow?.makeToast(message: "Error creating a file :- \(writeError.localizedDescription)")
})
}
} else {
UIApplication.shared.keyWindow?.makeToast(message: "Error downloading the file")
}
}
task.resume()
}
}

现在下载后的文件打不开。提到的从 url 下载文件的代码是否有问题

最佳答案

downloadTask方法的CompletionHandler在全局(后台)队列中执行。您必须在主队列中呈现您的 ActivityViewController。

使用以下代码来呈现您的activityViewController:

DispatchQueue.main.async(execute: {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
viewController.present(activityViewController, animated: true, completion: nil)
})

而不仅仅是

let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
viewController.present(activityViewController, animated: true, completion: nil)

关于ios - 使用 urlsessiondownloadtask 从 url 下载文件后,文件无法打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57555075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com