Url minus query string in Objective-C

hpique picture hpique · Nov 24, 2010 · Viewed 16.6k times · Source

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?

Answer

Andree picture Andree · Jan 24, 2015

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