HiveHicks
HiveHicks

Reputation: 2334

UIApplication openURL: doesn't work with relative URLs

Here's the code:

NSURL *newsUrl = [NSURL URLWithString:@"/Document/News/1593" relativeToURL:[NSURL URLWithString:@"http://exist.ru"]];

// Outputs "http://exist.ru/Document/News/1593"
NSLog(@"%@", [newsUrl absoluteString]);

// works
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[newsUrl absoluteString]]];

// doesn't work
//[[UIApplication sharedApplication] openURL:newsUrl];

Is it Apple's bug?

Upvotes: 4

Views: 1397

Answers (3)

Paul Beyer
Paul Beyer

Reputation: 61

Seems to no longer be an issue in iOS 9.x.

For < iOS 9.x support, add this wonderfully useless step before the call to openURL:

//Construct your relative URL 
NSURL *url = [NSURL URLWithString:@"path/to/whatever" relativeToURL:
    [NSURL URLWithString:@"http://www.example.com"]];

//FIX
url = [NSURL URLWithString:url.absoluteString];

Upvotes: 0

CSmith
CSmith

Reputation: 13458

Not real clear on what you're trying to accomplish, but if you want to programmatically build your URL's with potentially different hosts or paths, why not something like this:

NSURL *newsUrl = [NSURL URLWithString:
 [NSString stringWithFormat:@"%@%@",@"http://exist.ru",@"/Document/News/1593"]];

[[UIApplication sharedApplication] openURL:newsUrl]; 

Upvotes: -1

frankWhite
frankWhite

Reputation: 1542

in my Xcode output for NSLog(@"NEW %@", newsUrl) where I declare newUrl as

NSURL *newsUrl = [NSURL URLWithString:@"/Document/News/1593" relativeToURL:[NSURL URLWithString:@"http://exist.ru"]]:

NSLog output is

/Document/News/1593 -- http://exist.ru

but for [newsUrl absoluteString]

NSLog output is

http://exist.ru/Document/News/1593

So I'd guess that [URLWithString: relativeToURL:] is giving you the URL in a different format. This is reason your result is invalid.

Upvotes: 2

Related Questions