Url minus query string in Objective-C

10 Solutions Collect From Internet About “Url minus query string in Objective-C”

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

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

Here is the Swift version of Andree’s answer, with some extra flavour –

extension NSURL {

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

You can call it like –

let urlMinusQueryString  = url.absoluteStringByTrimmingQuery()

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.

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

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

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.

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];

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.

Swift 3.0

extension URL {

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

I think what you’re looking for is baseUrl.