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

261 Views Asked by At

I have implemented Document Picker. Users can only pick pdf files. When the user selects pdf from Document Picker I get the file location of that pdf file. Ex. file://somepath/pdffile.pdf. Once I receive this file location URL, I want to change pdffile.pdf to newpdf.pdf and use that newly created file location.

1

There are 1 best solutions below

0
On BEST ANSWER

You can do it while you are moving/copying the file to your app's local storage.

Code

/// 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
    }
}