iOS: parse a URL into segments

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: (
    "https://stackoverflow.com/",
    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.

Leave a Comment