createSymbolicLinkAtURL :withDestinationURL:error:
Creates a symbolic link at the specified URL that points to an item at the given URL.
- (BOOL)createSymbolicLinkAtURL:(NSURL *)url withDestinationURL:(NSURL *)destURL error:(NSError **)error
Parameters
- url
- The file URL at which to create the new symbolic link. The last path component of the URL issued as the name of the link.
- destURL
- The file URL that contains the item to be pointed to by the link. In other words, this is the destination of the link.
- error
- On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nil
for this parameter if you do not want the error information.
Return Value of [NSFileManager createSymbolicLinkAtURL]
YES
if the symbolic link was created or NO
if an error occurred. This method also returns NO
if a file, directory, or link already exists at path.Discussion
This method does not traverse symbolic links contained in destPath, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component in
path
is a symbolic link, that link is not followed.
Example of [NSFileManager createSymbolicLinkAtURL]
- (void)createSymbolicLinksForURL:(NSURL *)url inDirectory:(NSURL *)directory {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtURL:url
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLIsDirectoryKey]
options:NSDirectoryEnumerationSkipsHiddenFiles | NSDirectoryEnumerationSkipsPackageDescendants
errorHandler:nil];
NSArray *resourceKeys = [NSArray arrayWithObjects:NSURLIsSymbolicLinkKey, NSURLIsDirectoryKey, nil];
for (NSURL *bundledURL in dirEnum) {
if ([[[bundledURL resourceValuesForKeys:resourceKeys error:nil] objectForKey:NSURLIsDirectoryKey] boolValue]) continue;
NSArray *bundledURLPathComponents = [bundledURL pathComponents];
NSURL *destinationURL = directory;
for (NSUInteger componentIndex = [bundledURLPathComponents count] - dirEnum.level; componentIndex < [bundledURLPathComponents count]; componentIndex++) {
destinationURL = [destinationURL URLByAppendingPathComponent:[bundledURLPathComponents objectAtIndex:componentIndex]];
}
if ([fileManager fileExistsAtPath:destinationURL.path]) {
if ([[[destinationURL resourceValuesForKeys:resourceKeys error:nil] objectForKey:NSURLIsSymbolicLinkKey] boolValue]) {
[fileManager removeItemAtURL:destinationURL error:nil];
}
else {
continue;
}
}
NSURL *container = [destinationURL URLByDeletingLastPathComponent];
if (![fileManager fileExistsAtPath:container.path]) [fileManager createDirectoryAtURL:container withIntermediateDirectories:YES attributes:nil error:nil];
NSError *error = nil;
[fileManager createSymbolicLinkAtURL:destinationURL withDestinationURL:bundledURL error:&error];
if (error) NSLog(@"Failed to create symbolic link for %@ (Error: %@)", bundledURL, error);
}
}