ohho ohho - 1 year ago 175
Objective-C Question

How to extract and remove scheme name from NSURL?

What is proper way to extract and remove scheme name and

from a

For example:

note://Hello -> @"Hello"
calc://3+4/5 -> @"3+4/5"


NSString *scheme = @"note://";
NSString *path = @"Hello";

for later use in:

[[NSNotificationCenter defaultCenter] postNotificationName:scheme object:path];


You can look at it like this (mostly untested code, but you get the idea):

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
    NSLog(@"scheme: %@", [url scheme]);
    NSLog(@"url: %@", url);
    NSLog(@"query: %@", [url query]);
    NSLog(@"host: %@", [url host]);
    NSLog(@"path: %@", [url path]);

    NSDictionary * dict = [self parseQueryString:[url query]];
    NSLog(@"query dict: %@", dict);

So you can do this:

NSString * strNoURLScheme = 
 [strMyURLWithScheme stringByReplacingOccurrencesOfString:[url scheme] withString:@""];

NSLog(@"URL without scheme: %@", strNoURLScheme);


- (NSDictionary *)parseQueryString:(NSString *)query
    NSMutableDictionary *dict = [[[NSMutableDictionary alloc] initWithCapacity:6] autorelease];
    NSArray *pairs = [query componentsSeparatedByString:@"&"];

    for (NSString *pair in pairs) {
        NSArray *elements = [pair componentsSeparatedByString:@"="];
        NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];        
        [dict setObject:val forKey:key];
    return dict;