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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With