Bogdan
Bogdan

Reputation: 597

Check if Directory is a Mount Point in Objective C in OSX

I am writing a little command line utility in Objective C which will check if a given path is a mount point, and if not, would mount a network share to it. I was going to write this in bash, but opted to try to learn Objective C instead. I am looking for Objective C equivalent of something like this:

mount | grep some_path

Basically a function I can use to test if a given path is currently used as a mount point. Any help would be appreciated. Thank you!

Upvotes: 5

Views: 2147

Answers (2)

user1687195
user1687195

Reputation: 9196

in swift:

func findMountPoint(shareURL: URL) -> URL?{

    guard let urls = self.mountedVolumeURLs(includingResourceValuesForKeys: [.volumeURLForRemountingKey], options: [.produceFileReferenceURLs]) else {return nil}

    for u in urls{

        guard let resources = try? u.resourceValues(forKeys: [.volumeURLForRemountingKey]) else{
            continue
        }

        guard let remountURL = resources.volumeURLForRemounting else{
            continue
        }

        if remountURL.host == shareURL.host && remountURL.path == shareURL.path{
            return u
        }
    } 

    return nil
}

Upvotes: 1

Bogdan
Bogdan

Reputation: 597

After some research I ended up using this code, in case any one needs it in the future:

        NSArray * keys = [NSArray arrayWithObjects:NSURLVolumeURLForRemountingKey, nil];
        NSArray * mountPaths = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:keys options:0];

        NSError * error;
        NSURL * remount;

        for (NSURL * mountPath in mountPaths) {
            [mountPath getResourceValue:&remount forKey:NSURLVolumeURLForRemountingKey error:&error];
            if(remount){
                if ([[[NSURL URLWithString:share] host] isEqualToString:[remount host]] && [[[NSURL URLWithString:share] path] isEqualToString:[remount path]]) {
                    printf("Already mounted at %s\n", [[mountPath path] UTF8String]);
                    return 0;
                }
            }
        }

Note, the NSURL share is passed into the function as the path to the remote share. Filtering by the remount key gives you a list of mountpoint for remote filesystems, as local filesystems do not have that key set.

Upvotes: 5

Related Questions