Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url minus query string in Objective-C

What's the best way to get an url minus its query string in Objective-C? An example:

Input:

http://www.example.com/folder/page.htm?param1=value1&param2=value2 

Output:

http://www.example.com/folder/page.htm 

Is there a NSURL method to do this that I'm missing?

like image 225
hpique Avatar asked Nov 24 '10 22:11

hpique


2 Answers

Since iOS 8/OS X 10.9, there is an easier way to do this with NSURLComponents.

NSURL *url = [NSURL URLWithString:@"http://hostname.com/path?key=value"]; NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];  urlComponents.query = nil; // Strip out query parameters. NSLog(@"Result: %@", urlComponents.string); // Should print http://hostname.com/path 
like image 114
Andree Avatar answered Sep 28 '22 02:09

Andree


There's no NSURL method I can see. You might try something like:

NSURL *newURL = [[NSURL alloc] initWithScheme:[url scheme]                                          host:[url host]                                          path:[url path]]; 

Testing looks good:

#import <Foundation/Foundation.h> int main(int argc, char *argv[]) {     NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];      NSURL *url = [NSURL URLWithString:@"http://www.abc.com/foo/bar.cgi?a=1&b=2"];     NSURL *newURL = [[[NSURL alloc] initWithScheme:[url scheme]                                               host:[url host]                                               path:[url path]] autorelease];     NSLog(@"\n%@ --> %@", url, newURL);     [arp release];     return 0; } 

Running this produces:

$ gcc -lobjc -framework Foundation -std=c99 test.m ; ./a.out  2010-11-25 09:20:32.189 a.out[36068:903]  http://www.abc.com/foo/bar.cgi?a=1&b=2 --> http://www.abc.com/foo/bar.cgi 
like image 27
Simon Whitaker Avatar answered Sep 28 '22 03:09

Simon Whitaker