46

What's an efficient way to take an NSURL object such as the following:

foo://name/12345 

and break it up into one string and one unsigned integer, where the string val is 'name' and the unsigned int is 12345?

I'm assuming the algorithm involves converting NSURL to an NSString and then using some components of NSScanner to finish the rest?

4 Answers 4

195

I can only add an example here, the NSURL class is the one to go. This is not complete but will give you a hint on how to use NSURL:

NSString *url_ = @"foo://name.com:8080/12345;param?foo=1&baa=2#fragment";
NSURL *url = [NSURL URLWithString:url_];

NSLog(@"scheme: %@", [url scheme]); 
NSLog(@"host: %@", [url host]); 
NSLog(@"port: %@", [url port]);     
NSLog(@"path: %@", [url path]);     
NSLog(@"path components: %@", [url pathComponents]);        
NSLog(@"parameterString: %@", [url parameterString]);   
NSLog(@"query: %@", [url query]);       
NSLog(@"fragment: %@", [url fragment]);

output:

scheme: foo
host: name.com
port: 8080
path: /12345
path components: (
    "/",
    12345
)
parameterString: param
query: foo=1&baa=2
fragment: fragment

This Q&A NSURL's parameterString confusion with use of ';' vs '&' is also interesting regarding URLs.

4
  • Thanks for writing all of this out
    – Sneakyness
    Jan 25, 2013 at 23:16
  • 1
    In my experience, using pathComponents is risky. Indeed, if your path components contain a /, EVEN ENCODED, pathComponents will decode it and consider it as a separator. I'd rather parse the path components myself. Jan 23, 2015 at 10:06
  • everything seems to work except [url parameterString]...any ideas why that might be "(null)" if the [url absoluteString] contains exactly what I want?
    – whyoz
    Sep 10, 2015 at 20:25
  • here's a list of all NSURL components: i-phone-dev.blogspot.com/2013/08/nsurl-components.html This actually shows the parameterString as (null) too?
    – whyoz
    Sep 10, 2015 at 20:45
21

NSURL has a method pathComponents, which returns an array with all the different path components. That should help you get the integer part. To get the name I'd use the host method of the NSURL. The docs say, that it should work if the URL is properly formatted, might as well give it a try then.

All in all, no need to convert into a string, there seems to be plenty of methods to work out the components of the URL from the NSURL object itself.

1
  • This is true for the Swift URL type too. Sep 9, 2019 at 21:49
12

Actually there is a better way to parse NSURL. Use NSURLComponents. Here is a simle example:

Swift:

extension URL {
    var params: [String: String]? {
        if let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) {
            if let queryItems = urlComponents.queryItems {
                var params = [String: String]()
                queryItems.forEach{
                    params[$0.name] = $0.value
                }
                return params
            }
        }
        return nil
    }
}

Objective-C:

NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
    NSArray *queryItems = [components queryItems];

    NSMutableDictionary *dict = [NSMutableDictionary new];

    for (NSURLQueryItem *item in queryItems)
    {
        [dict setObject:[item value] forKey:[item name]];
    }
0
0

Thanks to Nick for pointing me in the right direction.

I wanted to compare file urls but was having problems with extra slashes making isEqualString useless. You can use my example below for comparing two urls by first de-constructing them and then comparing the parts against each other.

- (BOOL) isURLMatch:(NSString*) url1 url2:(NSString*) url2
{
    NSURL *u1 = [NSURL URLWithString:url1];
    NSURL *u2 = [NSURL URLWithString:url2];

    if (![[u1 scheme] isEqualToString:[u2 scheme]]) return NO;
    if (![[u1 host] isEqualToString:[u2 host]]) return NO;
    if (![[url1 pathComponents] isEqualToArray:[url2 pathComponents]]) return NO;

    //check some properties if not nil as isEqualSting fails when comparing them
    if ([u1 port] && [u2 port])
    {
        if (![[u1 port] isEqualToNumber:[u2 port]]) return NO;
    }

    if ([u1 query] && [u2 query])
    {
        if (![[u1 query] isEqualToString:[u2 query]]) return NO;
    }
    return YES;
}  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.