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.swift455 chars10 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.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