用户从文档选择器中选择后,以编程方式更改 pdf 文件的名称

Change name of pdf file programmatically after user selects it from Document Picker

我已经实现了文档选择器。用户只能选择 pdf 文件。当用户从文档选择器中选择 pdf 时,我会得到该 pdf 文件的文件位置。前任。文件://somepath/pdffile.pdf。收到此文件位置 URL 后,我想将 pdffile.pdf 更改为 newpdf.pdf 并使用新创建的文件位置。

您可以在将文件 moving/copying 保存到应用的本地存储时执行此操作。

代码

/// When you finish picking up a file, you get it's current location in the delegate callback like this.
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    
    /// Assumption is that you are picking only one file at a time.
    guard let url = urls.first else { return }
    
    do {
        /// You can copy this move this file to your Documents directory
        let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let newFileName = "custom_name.pdf"
        let newFilePath = "\(documentsDirectory)/\(newFileName)"
        try FileManager.default.moveItem(at: url, to: URL(fileURLWithPath: newFilePath))
    } catch {
        /// Handle error
    }
}