UIApplication openURL: does not work with relative URLs

Here is 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 this an Apple bug?

+4
source share
3 answers

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

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

but for [newsUrl absoluteString]

NSLog output

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

So, I assume that [URLWithString: relativeToURL:] provides you with a URL in a different format. This is the reason your result is invalid.

+2
source

It seems no longer a problem in iOS 9.x.

iOS 9.x, add this surprisingly useless step before calling 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]; 
0
source

It's not entirely clear what you are trying to accomplish, but if you want to programmatically build your URL 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]; 
-1
source

All Articles