Url minus query string in Objective-C

2019-02-16 04:46发布

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条回答
戒情不戒烟
2楼-- · 2019-02-16 05:00

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];
  }
查看更多
该账号已被封号
3楼-- · 2019-02-16 05:05

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.

查看更多
老娘就宠你
4楼-- · 2019-02-16 05:06

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.

查看更多
The star\"
5楼-- · 2019-02-16 05:07

I think what you're looking for is baseUrl.

查看更多
狗以群分
6楼-- · 2019-02-16 05:11

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!

查看更多
戒情不戒烟
7楼-- · 2019-02-16 05:15

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

NSString *result = [[url host] stringByAppendingPathComponent:[url path]];
查看更多
登录 后发表回答