【问题标题】:After downloading the file from url using urlsessiondownloadtask the file is not opening使用 urlsessiondownloadtask 从 url 下载文件后,文件未打开
【发布时间】:2019-12-24 13:48:10
【问题描述】:

当我尝试从 url 下载文件时,文件被下载并存储在 files 文件夹中。但是当我尝试打开文件时。文件似乎已损坏,我无法打开 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 下载文件的代码是否有任何问题

【问题讨论】:

  • 您在哪里添加文件扩展名?
  • @AshishGupta 我将文件名发送为“filename.pdf”
  • 您不能将下载的文件内容与服务器版本进行比较,看看您是否正确下载了文件。然后您就知道问题是否出在您的下载代码中。
  • 为什么获取目录的内容并检查文件?你有网址。
  • @vadian 获取内容不是你的意思??

标签: ios swift nsurlsessiondownloadtask


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多