Url减去Objective-C中的查询字符串

时间:2010-11-24 22:00:12

标签: objective-c url nsstring nsurl

在Objective-C中获取网址减去其查询字符串的最佳方法是什么?一个例子:

输入:

http://www.example.com/folder/page.htm?param1=value1&param2=value2

输出:

http://www.example.com/folder/page.htm

我缺少一个NSURL方法吗?

11 个答案:

答案 0 :(得分:38)

自iOS 8 / OS X 10.9起,使用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 :(得分:37)

我看不到NSURL方法。你可能会尝试类似的东西:

NSURL *newURL = [[NSURL alloc] initWithScheme:[url scheme]
                                         host:[url host]
                                         path:[url path]];

测试看起来不错:

#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;
}

运行它会产生:

$ 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

答案 2 :(得分:12)

以下是Andree's answer的Swift版本,带有一些额外的味道 -

extension NSURL {

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

您可以将其称为 -

let urlMinusQueryString  = url.absoluteStringByTrimmingQuery()

答案 3 :(得分:3)

您可能需要的是url的主机和路径组件的组合:

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

答案 4 :(得分:3)

您可以尝试使用query NSURL获取参数,然后使用stringByReplacingOccurrencesOfString NSString删除该值?

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

请注意,最终的网址仍将以?结尾,但如果需要,您也可以轻松删除。

答案 5 :(得分:2)

NSURL有一个query属性,其中包含GET网址中?之后的所有内容。所以简单地从absoluteString的末尾减去它,你就得到了没有查询的url。

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

日志:

Output: https://winker@127.0.0.1:1000/file/path/

+1适用于不属于?的{​​{1}}。

答案 6 :(得分:1)

我认为-baseURL可能会做你想要的。

如果没有,你可以通过NSString进行往返:

NSString *string = [myURL absoluteString];
NSString base = [[string componentsSeparatedByString:@"?"] objectAtIndex:0];
NSURL *trimmed = [NSURL URLWithString:base];

答案 7 :(得分:1)

Swift版本

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

希望这有帮助!

答案 8 :(得分:0)

您可能会喜欢replaceOccurrencesOfString:withString:options:range:类的方法NSMutableString。我通过为NSURL编写category来解决这个问题:

#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

这样,我可以将此消息发送到现有的NSURL个对象,并将一个新的NSURL对象返回给我。

我使用此代码测试了它:

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

我得到了以下输出(减去时间戳):

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

请注意,问号('?')仍然存在。我将把它留给读者以安全的方式将其删除。

答案 9 :(得分:0)

我们应该尝试使用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];
  }

答案 10 :(得分:-1)

我认为你要找的是baseUrl