Step Fifteen

Now we’ll write the code to handle the main logic intent: renaming the files and outputting the results.

We’ll use all of our validated parameters to return an array of identical INFiles with new names, or we’ll display an error if there’s a problem.

func handle(intent: RenameFilesIntent, completion: @escaping (RenameFilesIntentResponse) -> Void) { let files = intent.files ?? [] let position = intent.position let changeCase = intent.changeCase?.boolValue ?? false guard let dateFormat = intent.dateFormat else { completion(RenameFilesIntentResponse.failure(error: “Please choose a valid date format”)) return } var outputArray = [INFile]() for file in files { var newName = file.filename if changeCase { let newCase = intent.newCase switch newCase { case .lowercase: newName = newName.lowercased() case .uppercase: newName = newName.uppercased() default: completion(RenameFilesIntentResponse.failure(error: “An invalid case was selected”)) return } } switch position { case .append: guard let fileURL = file.fileURL else { completion(RenameFilesIntentResponse.failure(error: “Couldn’t get file URL of \(file.filename)”)) return } let filePath = fileURL.deletingPathExtension().lastPathComponent let nameNoExt = FileManager.default.displayName(atPath: filePath) let ext = fileURL.pathExtension newName = “\(nameNoExt)_\(dateFormat).\(ext)” case .prepend: newName = “\(dateFormat)_\(newName)” default: completion(RenameFilesIntentResponse.failure(error: “An invalid position was selected”)) return } let renamedFile = INFile(data: file.data, filename: newName, typeIdentifier: file.typeIdentifier) outputArray.append(renamedFile) } completion(RenameFilesIntentResponse.success(result: outputArray)) }

Here’s the complete, commented intent handler: