0

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!

1
  • Unclear what the problem is. You are the one who is throwing away the URL and turning it into its lastPathComponent. If you wanted the whole URL, don't do that. — Also, please always show real code. Copy and paste your actual code into the question. Do not show nonsense that is just typed directly into the question. Commented Dec 31, 2021 at 15:55

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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.).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.