What is the code necessary to create a Finder alias from a Cocoa application? Are there any differences for that code between OS X 10.5, 10.6, and 10.7?
Since OS X 10.6 you can use NSUrl
's writeBookmarkData:toURL:options:error:
method
From the documentation:
Creates an alias file on disk at a specified location with specified bookmark data.
Sample code:
NSURL *originalUrl = [NSURL fileURLWithPath:@"/this/is/your/path"];
NSURL *aliasUrl = [NSURL fileURLWithPath:@"/your/alias/path"];
NSData *bookmarkData = [originalUrl bookmarkDataWithOptions: NSURLBookmarkCreationSuitableForBookmarkFile includingResourceValuesForKeys:nil relativeToURL:nil error:NULL];
if(bookmarkData != nil) {
BOOL success = [NSURL writeBookmarkData:bookmarkData toURL:aliasUrl options:NSURLBookmarkCreationSuitableForBookmarkFile error:NULL];
if(NO == success) {
//error
}
}
However, aliases created in that way are not backwards-compatible to earlier OS X versions (pre 10.6)
Take a look at How to Create an Alias Programmatically.
- (void)makeAliasToFolder:(NSString *)destFolder inFolder:(NSString *)parentFolder withName:(NSString *)name
{
// Create a resource file for the alias.
FSRef parentRef;
CFURLGetFSRef((CFURLRef)[NSURL fileURLWithPath:parentFolder], &parentRef);
HFSUniStr255 aliasName;
FSGetHFSUniStrFromString((CFStringRef)name, &aliasName);
FSRef aliasRef;
FSCreateResFile(&parentRef, aliasName.length, aliasName.unicode, 0, NULL, &aliasRef, NULL);
// Construct alias data to write to resource fork.
FSRef targetRef;
CFURLGetFSRef((CFURLRef)[NSURL fileURLWithPath:destFolder], &targetRef);
AliasHandle aliasHandle = NULL;
FSNewAlias(NULL, &targetRef, &aliasHandle);
// Add the alias data to the resource fork and close it.
ResFileRefNum fileReference = FSOpenResFile(&aliasRef, fsRdWrPerm);
UseResFile(fileReference);
AddResource((Handle)aliasHandle, 'alis', 0, NULL);
CloseResFile(fileReference);
// Update finder info.
FSCatalogInfo catalogInfo;
FSGetCatalogInfo(&aliasRef, kFSCatInfoFinderInfo, &catalogInfo, NULL, NULL, NULL);
FileInfo *theFileInfo = (FileInfo*)(&catalogInfo.finderInfo);
theFileInfo->finderFlags |= kIsAlias; // Set the alias bit.
theFileInfo->finderFlags &= ~kHasBeenInited; // Clear the inited bit to tell Finder to recheck the file.
theFileInfo->fileType = kContainerFolderAliasType;
FSSetCatalogInfo(&aliasRef, kFSCatInfoFinderInfo, &catalogInfo);
}
You can also use applescript
osascript -e 'tell application "Finder" to make alias file to POSIX file "/Applications/myapp.app" at POSIX file "/Applications/"'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With