Using URLs

This article describes various operations you can perform using NSURL with Mac OS X v10.6 and later.

Creating File Reference URLs

Sometimes you need a reference to a file that the user might move while your application is running. In this situation, a path-based URL is not useful since the path will change when the user moves the file but the URL will continue to point to the original location. File reference URLs provide a way to track a file by its ID. This means that the reference is valid even if the file’s name or location in the file system changes.

You create a file reference URL from an existing URL using the method fileReferenceURL:

NSURL *existingURL = <#A URL for an existing file or directory#>;
NSURL *fileReferenceURL = [existingURL fileReferenceURL];

The representations of the two URLS in the example are different:

existingURL = file://localhost/Users/me/MyFile.txt
fileReferenceURL = file:///.file/id=6238375.726492

Both the standard and file reference URLs are, however, valid URLs.

Two caveats apply to file reference URLs:

Working with Bookmarks and Aliases

You can create a persistent representation of a URL using bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error:. The options argument allows you to specify a number of aspects of the bookmarked URL, including file alias information. (This allows you to read a bookmark as an alias on versions of Mac OS X prior to 10.6.)

NSURL *url = <#Create a URL#>;
NSError *error = nil;
NSData *bookmarkData = [url bookmarkDataWithOptions:NSURLBookmarkCreationSuitableForBookmarkFile
                            includingResourceValuesForKeys:nil
                            relativeToURL:nil
                            error:&error];
if (bookmarkData == nil) {
    // Handle the error...
}

If you create a bookmark using the NSURLBookmarkCreationSuitableForBookmarkFile option, you can subsequently create an alias file from the bookmark using the class method writeBookmarkData:toURL:options:error:.

NSURL *bookmarkURL = <#Create a URL for the bookmark#>;
BOOL ok = [NSURL writeBookmarkData:bookmarkData toURL:bookmarkURL options:0 error:&error];
if (!ok) {
    // Handle the error...
}

If the bookmark URL points to a directory, an alias file is created in that directory with its name derived from the information in the bookmark data. If the URL points to a file, the alias file is created with the location and name specified by the bookmark URL, and its extension changed to .alias if it is not already.

You can recreate a URL from bookmark data using URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:.