Search code examples
objective-ccocoansfilemanager

Checking if file exists when file on an external device


A playlist file .m3u contains entries available on an external device (a USB key in this case) such as:

/Volumes/KINGSTON/folder/mytitle.mp3

I'd like to check if the file exists:

NSURL *url = [NSURL URLWithString:@"/Volumes/KINGSTON/folder/mytitle.mp3"];
NSFileManager *manager = [NSFileManager defaultManager];
NSLog(@"%d",[manager fileExistsAtPath:[url absoluteString]]); //returns 0. I expect 1

I also tried:

NSURL *u = [[NSURL alloc]initWithScheme:@"/Volumes" host:@"/KINGSTON" path:@"/folder/mytitle.mp3"];
NSLog(@"%d",[manager fileExistsAtPath:[u absoluteString]]); //0

What did I do wrong?

Thanks,

Roland


Solution

  • NSURL *url = [NSURL URLWithString:@"/Volumes/KINGSTON/folder/mytitle.mp3"];
    

    That string does not describe a URL. It's a pathname. Use fileURLWithPath:.

    NSLog(@"%d",[manager fileExistsAtPath:[url absoluteString]]);
    

    absoluteString does not return a path; it returns a string describing a URL. Use path.

    Or, better yet, use checkResourceIsReachableAndReturnError:.

    I also tried:

    NSURL *u = [[NSURL alloc]initWithScheme:@"/Volumes" host:@"/KINGSTON" path:@"/folder/mytitle.mp3"];
    

    /Volumes isn't a scheme, /KINGSTON isn't a host, and /folder/mytitle.mp3 is a path but does not refer to anything that exists.

    The scheme for a file URL is file:, and the host is generally either localhost or the empty string. The path of a file URL is the complete absolute path to the file.