Dae
Dae

Reputation: 2427

Is it possible to determine in Cocoa whether a file was opened from an alias?

The program I have in mind will need to be associated with all files ending with a specific extension (e.g. ".abc"), so it'll open when a user double clicks some "file.abc". Is it possible to determine in Cocoa when a user double-clicks an alias to such file?

Upvotes: 4

Views: 680

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

The application delegate will receive application:openFile: when launched this way. If that caused you to launch, application:openFile: will come between applicationWillFinishLaunching: and applicationDidFinishLaunching:. You may receive application:openFile: at other times, since you may already have been launched when the user double-clicks a document.


EDIT: Aliases are now called "bookmarks" (since 10.6). You use NSURL to read them. See the File System Programming Guide for full details, but here's a short example:

NSURL *aliasURL = [NSURL fileURLWithPath:@"..."];
NSData *alias = [NSURL bookmarkDataWithContentsOfURL:aliasURL error:&error];
if (alias == NULL) {
  NSLog(@"Failed aliasURL: %@", error);
}

BOOL isStale;
NSURL *realURL = [NSURL URLByResolvingBookmarkData:alias options:0 relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
if (isStale || realURL == NULL) {
  NSLog(@"Failed realURL: %@", error);
}

NSLog(@"realPath:%@", [realURL path]);

I'm not aware of any API that will tell you if a given NSURL is an alias other than trying to read it as one and seeing if it fails.

Keep in mind that users might also create the same situation using symbolic links.

Upvotes: 1

Related Questions