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:
main.swift86 chars3 linescurrentDirectoryPath 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:
main.swift202 chars3 linesHere, 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., Documents) using deletingLastPathComponent. This gives us the parent directory, which is the root directory. Finally, we convert the URL back to a path using .path property.
With this, we can find the root directory of any directory in our app's file system.
gistlibby LogSnag