【问题标题】:Download PDF and save to the "Files" in iPhone, not to the app data, Swift [duplicate]下载PDF并保存到iPhone中的“文件”,而不是应用程序数据,Swift [重复]
【发布时间】:2019-01-16 10:54:23
【问题描述】:

我尝试使用以下代码下载 pdf 文件。在这里它存储在应用程序数据中。但我需要在 iPhone 的 "Files" 文件夹中显示下载的 pdf。

    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")

    //Create URL to the source file you want to download
    let fileURL = URL(string: "http://swift-lang.org/guides/tutorial.pdf")

    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
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }

            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()

有可能吗?

【问题讨论】:

  • 不,不可能保存在 iPhone 中,您只存储在 App Data 中或上传到 iCloud。
  • @NikunjKumbhani 所以用户不能选择他想保存文件的地方?
  • @Purpose 您可以在上传到 iCloud 之前从用户那里获得确认警报,然后您就可以执行此操作。要显示此文件,您可以使用 DocumentViwer。
  • 我想了解更多@NikunjKumbhani。可以提供一个链接来学习吗?
  • stackoverflow.com/a/42370660/10150796 根据您的要求尝试从任何资源中选择文档以用于显示目的,您只需将服务器 URL 传递给 QLPreviewingController 即可。

标签: ios swift file pdf download


【解决方案1】:

这是下载任何文件并保存到照片(如果是图像文件)或文件(如果是 pdf)的方法

let urlString = "your file url"
let url = URL(string: urlString)
let fileName = String((url!.lastPathComponent)) as NSString
// Create destination URL
let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
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
        if let statusCode = (response as? HTTPURLResponse)?.statusCode {
            print("Successfully downloaded. Status code: \(statusCode)")
        }
        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)
                        self.present(activityViewController, animated: true, completion: nil)
                    }
                }
            }
            catch (let err) {
                print("error: \(err)")
            }
        } 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()

【讨论】:

    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 2019-02-16
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2018-11-03
    • 2012-05-07
    相关资源
    最近更新 更多