Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 957
lupidan Avatar asked Apr 09 '13 07:04

lupidan


People also ask

What is the difference between NSURL and URL?

They are identical in usage, Apple has chosen to drop the NeXTSTEP prefix in support of using foundation with Swift on multiple platforms like iOS, Android, and Linux. from Apple: "The Swift overlay to the Foundation framework provides the URL structure, which bridges to the NSURL class.

What is NSURL in Swift?

An object representing the location of a resource that bridges to URL ; use NSURL when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

How do I find Baseurl?

Everything that follows it is known as a URL path. To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.


1 Answers

Docs for BaseURL.

baseURL
Returns the base URL of the receiver.

- (NSURL *)baseURL
Return Value
The base URL of the receiver. If the receiver is an absolute URL, returns nil.

Availability
Available in iOS 2.0 and later.
Declared In
NSURL.h

Seems it only works for relative URLs.

You could possibly use ...

NSArray *pathComponents = [url pathComponents]

and then take the bits you want.

Or try...

NSString *host = [url host];
like image 61
Fogmeister Avatar answered Sep 25 '22 05:09

Fogmeister