To find the root directory or the absolute path of a directory in Swift, we can use the
FileManager class provided by the Foundation framework. Here's the code snippet:
let fileManager = FileManager.default let rootPath = fileManager.currentDirectoryPath86 chars3 lines
currentDirectoryPath returns the absolute pathname of the current working directory of the process. This is the directory from where the app is executed, and its parent is the root directory.
We can also specify a specific directory for which we want to find the root directory. For example, if we want to find the root directory for the
Documents directory of the app, we can use the following code snippet:
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let rootPath = URL(fileURLWithPath: documentDirectoryPath).deletingLastPathComponent().path202 chars3 lines
Here, we first get the path of the
Documents directory using
NSSearchPathForDirectoriesInDomains. Then, we convert this path to a URL and remove the last path component (i.e.,
deletingLastPathComponent. This gives us the parent directory, which is the root directory. Finally, we convert the URL back to a path using
With this, we can find the root directory of any directory in our app's file system.