Search code examples
objective-cmacoscocoansurlnsfilemanager

NSURL bookmark lookup failing


I'm trying to store bookmark references to a collection of NSURLs, but bookmarkDataWithContentsOfURL seems to be failing every time, even for files that I have permission to access. My app is not (yet) sandboxed, so that is not the problem.

I am reading these files in other ways (both via C-based and Cocoa APIs) with no problems.

I am iterating over a directory and trying to read the bookmark data like so:

NSArray * contents = [[NSFileManager defaultManager] 
    contentsOfDirectoryAtURL:directoryURL 
    includingPropertiesForKeys:keys options:0 error:&error];

for (NSURL * url in contents)
{
    NSData * bookmarkData = [NSURL bookmarkDataWithContentsOfURL:url error:&error];

    if (error)
    {
        NSLog(@"Error finding bookmark for %@: %@", url, error);
    }
}

For all regular files, I am getting the following error:

Error finding bookmark for file://localhost/Users/mspong/foo/bar.pdf: 
Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened."

For all directories, I am getting:

Error finding bookmark for file://localhost/Users/mspong/foo/: 
Error Domain=NSPOSIXErrorDomain Code=21 "The operation couldn’t be completed. Is a directory"

Why am I getting this error for files that I certainly have permission to open? And does the second error mean that bookmarks are not available for directories? Is there any alternative way to save a persistent identifier for a directory that survives renames/moves?


Solution

  • The function bookmarkDataWithContentsOfURL:error: retrieves the bookmark data from an alias file.

    To create bookmark data for a URL, use

    bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error:
    

    See Locating Files Using Bookmarks in the "File System Programming Guide".