NSURL baseURL returns nil. Any other way to get the actual base URL

Lupi picture Lupi · Apr 9, 2013 · Viewed 10.6k times · Source

I think I don't understand the concept of "baseURL". This:

NSLog(@"BASE URL: %@ %@", [NSURL URLWithString:@"http://www.google.es"], [[NSURL URLWithString:@"http://www.google.es"] baseURL]);

Prints this:

BASE URL: http://www.google.es (null)

And of course, in the Apple docs I read this:

Return Value The base URL of the receiver. If the receiver is an absolute URL, returns nil.

I'd like to get from this example URL:

https://www.google.es/search?q=uiviewcontroller&aq=f&oq=uiviewcontroller&sourceid=chrome&ie=UTF-8

This base URL

https://www.google.es

My question is simple. Is there any cleaner way of getting the actual base URL without concatenating the scheme and the hostname? I mean, what's the purpose of base URL then?

Answer

Mike Abdullah picture Mike Abdullah · Apr 9, 2013

-baseURL is a concept purely of NSURL/CFURL rather than URLs in general. If you did this:

[NSURL URLWithString:@"search?q=uiviewcontroller"
       relativeToURL:[NSURL URLWithString:@"https://www.google.es/"]];

then baseURL would be https://www.google.es/. In short, baseURL is only populated if the NSURL is created using a method that explicitly passes in a base URL. The main purpose of this feature is to handle relative URL strings such as might be found in the source of a typical web page.

What you're after instead, is to take an arbitrary URL and strip it back to just the host portion. The easiest way I know to do this is a little cunning:

NSURL *aURL =  [NSURL URLWithString:@"https://www.google.es/search?q=uiviewcontroller"];
NSURL *hostURL = [[NSURL URLWithString:@"/" relativeToURL:aURL] absoluteURL];

This will give a hostURL of https://www.google.es/

I have such a method published as -[NSURL ks_hostURL] as part of KSFileUtilities (scroll down the readme to find it documented)

If you want purely the host and not anything like scheme/port etc. then -[NSURL host] is your method.