Search code examples
cocoansstringnsurl

Grabbing everything past the domain in an NSURL?


This seems simple, but I haven't been able to find anything that does precisely what I'm looking for.

What I need is the ability the take an NSURL (or its NSString representation) and grab everything past the scheme and domain. So in the case of http://www.google.com/search?&q=cocoa, I need /search?&q=cocoa.

I can come close by cobbling together a string using [NSURL relativePath] and [NSURL query], but [NSURL query] leaves out question marks, and since the URLs I'm working with aren't guaranteed to have question marks I can't just add them back in myself.

So is there a nice, convenient way to grab everything past the scheme and domain that I've missed or am I going to have to pull it all apart and glue it back together?


Solution

  • You can do this with regular expressions etc. But in this case a custom solution might be best.

    If your URL is always "http://..." then you need to locate the first "/" after the first 7 characters, and then take the string from there. Or you can just locate the 3rd "/"...

    You can calculate the index of that "/" using one of the rangeX methods of NSString, and use the substringFromIndex method once you have it.