Returning the Volume Name of a Folder or a Volume

Viewed 1499

I need to get the volume name of any folder that the user selects. In reference to this topic, I've created the following function.

- (NSString *)getVolumeName:(NSString *)path {
    // path is the path of a folder
    NSURL *url = [NSURL fileURLWithPath:[path stringByDeletingLastPathComponent]];
    NSError *error;
    NSString *volumeName;
    [url getResourceValue:&volumeName forKey:NSURLVolumeNameKey error:&error];
    return volumeName;
}

It works in most cases. If the user selects a mounted volume, it can fail, though. For example, I have an SDHC card inserted into the card slot of an iMac. If I select this volume instead of a folder inside of it, the function above can return the name of the hard disk drive. What is an infallible manner of returning the volume name of a folder or a volume? Maybe use AppleScript?

Thank you,

UPDATE

Maybe something like the following?

- (NSString *)getVolumeName:(NSString *)path {
    NSURL *url = [NSURL fileURLWithPath:[path stringByDeletingLastPathComponent]];
    if ([[url path] isEqualTo:@"/Volumes"]) {
        return [path lastPathComponent];
    } else {
        NSError *error;
        NSString *volumeName;
        [url getResourceValue:&volumeName forKey:NSURLVolumeNameKey error:&error];
        return volumeName; 
    }
}
3 Answers

This is what I use

-(NSString *)volumeNameForPath:(NSString *)path
{       
    NSArray* components = [[NSFileManager defaultManager] componentsToDisplayForPath:path];
    NSString* volumeName = components.first ?: "Unknown";       
    return volumeName;
}

Swift:

FileManager.default.componentsToDisplay(forPath: url.path)?.first

or:

extension URL {

    func volumeName() -> String? {
        guard let resourceValues = try? resourceValues(forKeys: [.volumeNameKey]) else {
            return nil
        }

        return resourceValues.volumeName
    }

}
Related