【问题标题】:How to save a POST request response as a PDF file persistently such that user may open it from outside the app later in iOS app?如何将 POST 请求响应永久保存为 PDF 文件,以便用户稍后可以在 iOS 应用程序中从应用程序外部打开它?
【发布时间】:2021-04-02 15:47:51
【问题描述】:

我正在开发一个 iOS 应用程序。在应用程序中,我使用 Alamofire 创建一个 POST 请求,该请求返回一个原始 PDF 文件作为响应。现在,我可以保存文件并使用UIDocumentInteractionController 打开它。但是,我希望文件保留在用户的文档文件夹中。 以下是我创建目标路径的方法:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in 
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent("Dividend Summary Report.pdf")
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

请有人告诉我我的逻辑有什么问题以及我可以做些什么来纠正它。

【问题讨论】:

    标签: ios swift pdf post alamofire


    【解决方案1】:

    你需要检查文件状态是否存在,然后从documentDirectory读取,否则下载文件。

    像这样创建函数:

    func checkIfFileExists(urlString: String) {
            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
            let url = NSURL(fileURLWithPath: path)
            let fileName = urlString
            let fileManager = FileManager.default
            let filePath = url.appendingPathComponent("\(fileName).pdf")?.path
            print("filePath : \(String(describing: filePath))")
            if fileManager.fileExists(atPath: filePath!) {
                print("File exists")
              
            } else {
                print("File doesn't exists")
                // set your download function here
            }
        }
    

    【讨论】:

    • 这不是我需要的。如果存在,我已经覆盖了任何以前的文件。我需要一种可以将文件永久保存在存储中的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多