如何将POST请求响应永久保存为PDF文件,以便用户稍后在iOS应用程序中从应用程序外部打开它



我正在开发一个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])
}

有人请告诉我我的逻辑出了什么问题,我能做些什么来纠正它。

您需要检查文件状态(如果存在(,然后从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
}
}

相关内容

最新更新