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!
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