31

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?

11 Answers 11

49

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
1
  • I have just found out that this method is not working in iOS 7. Encountered -'[__NSConcreteURLComponents string]: unrecognized selector sent to instance 0x167a12d0'. It's fine working on iOS 8 and iOS 9.
    – felixwcf
    Apr 18, 2016 at 3:19
38

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
3
  • 4
    Nice solution, the only problem with it is that the port will not be carried over.
    – Pascal
    Jan 5, 2012 at 20:18
  • Another problem with this is that this will crash the app if the path is not present in the original url. Sep 19, 2017 at 19:15
  • This API is actually API_DEPRECATED. People should stop using it and turn to NSURLComponents instead. Nov 21, 2018 at 7:07
19

Here is the Swift version of Andree's answer, with some extra flavour -

extension NSURL {

    func absoluteStringByTrimmingQuery() -> String? {
        if var urlcomponents = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) {
            urlcomponents.query = nil
            return urlcomponents.string
        }
        return nil
    }
}

You can call it like -

let urlMinusQueryString  = url.absoluteStringByTrimmingQuery()
1
  • Thanks a lot. I just made the change @bcattle
    – BLC
    May 31, 2018 at 20:05
9

Swift Version

extension URL {
    func absoluteStringByTrimmingQuery() -> String? {
        if var urlcomponents = URLComponents(url: self, resolvingAgainstBaseURL: false) {
            urlcomponents.query = nil
            return urlcomponents.string
        }
        return nil
    }
}

Hope this helps!

3

What you probably need is a combination of url's host and path components:

NSString *result = [[url host] stringByAppendingPathComponent:[url path]];
3

You could try using query of NSURL to get the parameters, then strip that value using stringByReplacingOccurrencesOfString of NSString?

NSURL *before = [NSURL URLWithString:@"http://www.example.com/folder/page.htm?param1=value1&param2=value2"];
NSString *after = [before.absoluteString stringByReplacingOccurrencesOfString:before.query withString:@""];

Note, the final URL will still end with ?, but you could easily strip that as well if needed.

2

I think -baseURL might do what you want.

If not, you can can do a round trip through NSString like so:

NSString *string = [myURL absoluteString];
NSString base = [[string componentsSeparatedByString:@"?"] objectAtIndex:0];
NSURL *trimmed = [NSURL URLWithString:base];
1
  • No -baseURL will not do what you want.
    – JeremyP
    Nov 25, 2010 at 10:37
2

NSURL has a query property which contains everything after the ? in a GET url. So simply subtract that from the end of the absoluteString, and you've got the url without the query.

NSURL *originalURL = [NSURL URLWithString:@"https://[email protected]:1000/file/path/?q=dogfood"];
NSString *strippedString = [originalURL absoluteString];
NSUInteger queryLength = [[originalURL query] length];
strippedString = (queryLength ? [strippedString substringToIndex:[strippedString length] - (queryLength + 1)] : strippedString);
NSLog(@"Output: %@", strippedString);

Logs:

Output: https://[email protected]:1000/file/path/

The +1 is for the ? which is not part of query.

0

You might fancy the method replaceOccurrencesOfString:withString:options:range: of the NSMutableString class. I solved this by writing a category for NSURL:

#import <Foundation/Foundation.h>

@interface NSURL (StripQuery)
// Returns a new URL with the query stripped out.
// Note: If there is no query, returns a copy of this URL.
- (NSURL *)URLByStrippingQuery;
@end

@implementation NSURL (StripQuery)
- (NSURL *)URLByStrippingQuery
{
    NSString *query = [self query];
    // Simply copy if there was no query. (query is nil if URL has no '?',
    // and equal to @"" if it has a '?' but no query after.)
    if (!query || ![query length]) {
        return [self copy];
    }
    NSMutableString *urlString = [NSMutableString stringWithString:[self absoluteString]];
    [urlString replaceOccurrencesOfString:query
                               withString:@""
                                  options:NSBackwardsSearch
                                    range:NSMakeRange(0, [urlString length])];
    return [NSURL URLWithString:urlString];
}
@end

This way, I can send this message to existing NSURL objects and have a new NSURL object be returned to me.

I tested it using this code:

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURL *url = [NSURL URLWithString:@"http://www.example.com/script.php?key1=val1&key2=val2"];
//      NSURL *url = [NSURL URLWithString:@"http://www.example.com/script.php?"];
//      NSURL *url = [NSURL URLWithString:@"http://www.example.com/script.php"];
        NSURL *newURL = [url URLByStrippingQuery];
        NSLog(@"Original URL: \"%@\"\n", [url absoluteString]);
        NSLog(@"Stripped URL: \"%@\"\n", [newURL absoluteString]);
    }
    return 0;
}

and I got the following output (minus the time stamps):

Original URL: "http://www.example.com/script.php?key1=val1&key2=val2"
Stripped URL: "http://www.example.com/script.php?"

Note that the question mark ('?') still remains. I will leave it up to the reader to remove it in a secure way.

0

We should try to use NSURLComponents

  NSURL *url = @"http://example.com/test";
  NSURLComponents *comps = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:YES];
  NSString *cleanUrl = [NSString stringWithFormat:@"%@://%@",comps.scheme,comps.host];
  if(comps.path.length > 0){
     cleanUrl = [NSString stringWithFormat:@"%@/%@",cleanUrl,comps.path];
  }
-1

I think what you're looking for is baseUrl.

1
  • 1
    baseURL documentation has this scary clarification: "If the receiver is an absolute URL, returns nil." Not sure what an "absolute" url is, though.
    – hpique
    Nov 24, 2010 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.