Skip to content

Instantly share code, notes, and snippets.

@leiless
Created November 29, 2018 11:31
Show Gist options
  • Save leiless/b15d0f2b2767a34bc56afed78f656f85 to your computer and use it in GitHub Desktop.
Save leiless/b15d0f2b2767a34bc56afed78f656f85 to your computer and use it in GitHub Desktop.
(macOS) Fetch local removable mounted volumes
/**
* Probe local removable mounted volumes
* @return An array with NSURL objects
*/
+ (NSArray<NSURL *> *)probeRemovableMountedVolumes {
NSArray *keys = [NSArray arrayWithObjects:NSURLVolumeIsEjectableKey,
NSURLVolumeIsLocalKey, NSURLVolumeIsReadOnlyKey,
NSURLVolumeIsRemovableKey, nil];
NSArray *flags = [NSArray arrayWithObjects:@YES, @YES, @NO, @YES, nil];
NSAssert(keys.count == flags.count,
@"Inconsistent array size %lu vs %lu", keys.count, flags.count);
NSArray *urls = [[NSFileManager defaultManager]
mountedVolumeURLsIncludingResourceValuesForKeys:keys
options:NSVolumeEnumerationSkipHiddenVolumes];
NSMutableArray<NSURL *> *volumes = [[NSMutableArray alloc] init];
NSNumber *chk;
NSURLResourceKey key;
NSUInteger i;
for (NSURL *url in urls) {
for (i = 0; i < keys.count; i++) {
key = [keys objectAtIndex:i];
if (![url getResourceValue:&chk forKey:key error:nil])
break;
if ([chk boolValue] != [[flags objectAtIndex:i] boolValue])
break;
}
if (i == keys.count) [volumes addObject:url];
}
return volumes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment