rename a json file in swift

To rename a JSON file in Swift, we need to use the FileManager class which provides file handling capabilities. The following code demonstrates how to rename a JSON file:

main.swift
let fileManager = FileManager.default
let currentPath = Bundle.main.path(forResource: "currentFileName", ofType: "json") // specify the current file name
let newPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("newFileName.json") // specify the new file name and path

do {
   try fileManager.moveItem(atPath: currentPath!, toPath: newPath.path)
} catch {
   print("Error renaming file: \(error)")
}
455 chars
10 lines

Explanation:

  • fileManager is an instance of FileManager.
  • currentPath is the path to the JSON file that you want to rename. In this case, we are using the Bundle.main.path method to get the path to the JSON file in the app's main bundle.
  • newPath is the new path and file name for the JSON file. We are using FileManager.default.urls to specify the new path to the documents directory, appending the new file name with the .json extension.
  • The try block attempts to perform the file rename operation using fileManager.moveItem, which moves the file from the current path to the new path. If an error occurs, it will be caught in the catch block and printed to the console.

gistlibby LogSnag