Wednesday, May 1, 2013

NSURL URLByAppendingPathComponent example ios


URLByAppendingPathComponent:

Returns a new URL made by appending a path component to the original URL.
- (NSURL *)URLByAppendingPathComponent:(NSString *)pathComponent
Parameters of [NSURL URLByAppendingPathComponent]
pathComponent
The path component to add to the URL.
Return Value
A new URL with pathComponent appended.
Discussion of [NSURL URLByAppendingPathComponent]
If the original URL does not end with a forward slash and pathComponent does not begin with a forward slash, a forward slash is inserted between the two parts of the returned URL, unless the original URL is the empty string.
Example of [NSURL URLByAppendingPathComponent]
@interface NSURL ( Extensions )
- (NSURL*) urlByAppendingPathComponent: (NSString*) component;
@end

@implementation NSURL ( Extensions )
- (NSURL*) urlByAppendingPathComponent: (NSString*) component;
{
    CFURLRef newURL = CFURLCreateCopyAppendingPathComponent( kCFAllocatorDefault, (CFURLRef)[self absoluteURL], (CFStringRef)component, [component hasSuffix:@"/"] );
    return [NSMakeCollectable(newURL) autorelease];
}
@end
and then:
*base = [NSURL URLWithString:@"http://my.url/path"];
*suffix = @"sub/path";
NSURL *final = [base urlByAppendingPathComponent:suffix];
NSLog( @"%@", final );
// displays http://my.url/path/sub/path
Example of [NSURL URLByAppendingPathComponent]
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Database.sqlite"];

// If the database doesn't exist copy in the default one
if (![storeURL checkResourceIsReachableAndReturnError:NULL])
{
    NSURL *defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"Database" withExtension:@"sqlite"];

    if ([defaultStoreURL checkResourceIsReachableAndReturnError:NULL])
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
    }
}