Home > front end >  Get the name of file(s) within last directory and the full directory path using Swift
Get the name of file(s) within last directory and the full directory path using Swift

Time:01-01

I am trying to obtain the name of a file (JSON format but saved without an extension) within the last directory of a given path. Each file is saved with its own unique subpath inside the app's data container.

I also need to get the full path of the file, including the filename.

From what I've read, I believe it is better to use URLs to do this rather than using string paths.

I have tried the following code:

do {
    let enumerator = FileManager.default.enumerator(at: filePath, includingPropertiesForKeys: nil)
    while let element = enumerator?.nextObject() as? URL {
    var nexObject = element.lastPathComponent
        print(nextObject)
    }
} catch let error {
    print(error.localizedDescription)
}

This does seem to iterate through each level of the path until the end. Great, but what is the best way to get the full path, including the filename, other than concatenation of each object from the above?

All advice gratiously received. Thanks!

CodePudding user response:

As element is an URL, if you're interested in the full path name rather than the last component, just go for:

    var nextObject = element.absoluteURL  // instead of .lastPathComponent

or just

    var nextObject = element.path  // or even relativePath 

CodePudding user response:

Thank you, @Christophe ( 1)

I've also since spotted that the documentation for enumerator(at:includingPropertiesForKeys:options:errorHandler:) provides a nice example, which can be modifed for my purposes by using additional resource keys (e.g. name, path, etc.).

  • Related