Search code examples
cocoafile-attributes

get file attributes with nsfilesustem in cocoa no such file exists


I've searching for about 3 hours of how to get the creation date of a file, I get the URL with an enumerator, after that I pass it to path correcting the percents, and finally I try to get the file attributes...so, I don no alter the path in anyway but I always get the same error "The operation couldn’t be completed. No such file or directory", and the path "file:///Users/raul/Desktop/DSC_0386.JPG".

The code sample:

NSError* error = nil;
//NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:[[url absoluteString] stringByRemovingPercentEncoding] error:&error];
NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:@"file://Users/raul/Desktop/DSC_0386.JPG" error:&error];
NSLog(@"%@",error);
NSDate *fecha = [fileAttribs objectForKey:NSFileCreationDate];

I've commented the first NSDictionary to try out the second statement with the nsstring directly.

I've checked that my file already exists.

Please, any help?? I'm missing anything?


Solution

  • Several issues:

    1) In most cases, you shouldn't have to convert an NSURL to a path string in order to operate on a file. In particular, you can use the "resource value" API of NSURL to get the creation time directly:

    NSDate* creationDate;
    NSError* error;
    if ([url getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&error])
        /* use creationDate */;
    else
        /* handle error */;
    

    2) If you do need to get a path string from NSURL, don't use -absoluteString. That will still be a URL string, with things like "file://", etc. A URL string is not a valid path string. The error message you quoted in your question was already telling you this. It showed you a file "path" of "file:///Users/raul/Desktop/DSC_0386.JPG", but that's not a path at all.

    You should just use the -path method. You do not need to do anything with percent encoding when you get the -path.

    3) You should ignore any error output parameter until you have checked whether the method you called succeeded or failed, usually by examining its return value. That is, the code you posted should be reorganized like this:

    NSError* error = nil;
    NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:@"file://Users/raul/Desktop/DSC_0386.JPG" error:&error];
    if (fileAttribs)
    {
        NSDate *fecha = [fileAttribs objectForKey:NSFileCreationDate];
        // ... use fecha ...
    }
    else
        NSLog(@"%@",error);