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¶m2=value2
Output:
http://www.example.com/folder/page.htm
Is there a NSURL
method to do this that I'm missing?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With