Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the Volume Name of a Folder or a Volume

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; 
    }
}
like image 254
El Tomato Avatar asked Feb 15 '23 10:02

El Tomato


1 Answers

I cannot test this at the moment, but I think you should work directly on the given path, and not remove the last path component:

- (NSString *)getVolumeName:(NSString *)path {
    // path is the path of a folder
    NSURL *url = [NSURL fileURLWithPath:path];
    NSError *error;
    NSString *volumeName;
    [url getResourceValue:&volumeName forKey:NSURLVolumeNameKey error:&error];
    return volumeName;
}
like image 77
Martin R Avatar answered Feb 24 '23 13:02

Martin R