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?

hpique
  • 119,096
  • 131
  • 338
  • 476

11 Answers11

47

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
carbonr
  • 6,049
  • 5
  • 46
  • 73
Andree
  • 3,033
  • 6
  • 36
  • 56
  • 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 '16 at 03: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
Simon Whitaker
  • 20,506
  • 4
  • 62
  • 79
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()
BLC
  • 2,240
  • 25
  • 27
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!

Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
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.

Dale Zak
  • 1,106
  • 13
  • 22
3

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

NSString *result = [[url host] stringByAppendingPathComponent:[url path]];
Vladimir
  • 170,431
  • 36
  • 387
  • 313
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://winker@127.0.0.1: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://winker@127.0.0.1:1000/file/path/

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

Kenny Winker
  • 11,919
  • 7
  • 56
  • 78
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];
NSResponder
  • 16,861
  • 7
  • 32
  • 46
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.

Victor Zamanian
  • 3,100
  • 24
  • 31
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];
  }
Jidong Chen
  • 450
  • 6
  • 9
-1

I think what you're looking for is baseUrl.

Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
  • 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 '10 at 22:22