John Wells
John Wells

Reputation: 1149

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?

Upvotes: 1

Views: 475

Answers (3)

Nariman
Nariman

Reputation: 6426

Isn't this exactly what [NSURL relativeString] does?

One minor note of caution on this:

enter image description here

Upvotes: 3

Rob Keniger
Rob Keniger

Reputation: 46030

If the URL doesn't have a question mark to denote its parameter string then all of the parameters should be returned as part of the path. For NSURL to return something from ‑query, there must be a question mark in the URL.

The other things that can come after the path are ‑fragment and ‑parameterString. URLs basically break down like this:

scheme://user:[email protected]:portnumber/path/file.htm;param1;param2?something=other&andmore=more#fragments

If ‑query returns nil then there is no question mark.

Upvotes: 1

CRD
CRD

Reputation: 53010

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.

Upvotes: 1

Related Questions