Objective-C:如何将查询参数添加到NSURL?

ma1*_*w28 56 objective-c nsurl query-string

比方说我有一个NSURL?它是否已经有一个空的查询字符串,我如何添加一个或多个参数给queryNSURL?即,有没有人知道这个功能的实现?

- (NSURL *)URLByAppendingQueryString:(NSString *)queryString
Run Code Online (Sandbox Code Playgroud)

这样它就满足了这个NSURL+AdditionsSpec.h文件:

#import "NSURL+Additions.h"
#import "Kiwi.h"

SPEC_BEGIN(NSURL_AdditionsSpec)

describe(@"NSURL+Additions", ^{
    __block NSURL *aURL;

    beforeEach(^{
        aURL = [[NSURL alloc] initWithString:@"http://www.example.com"];
        aURLWithQuery = [[NSURL alloc] initWithString:@"http://www.example.com?key=value"];
    });

    afterEach(^{
        [aURL release];
        [aURLWithQuery release];
    });

    describe(@"-URLByAppendingQueryString:", ^{
        it(@"adds to plain URL", ^{
            [[[[aURL URLByAppendingQueryString:@"key=value&key2=value2"] query] should]
             equal:@"key=value&key2=value2"];
        });

        it(@"appends to the existing query sting", ^{
            [[[[aURLWithQuery URLByAppendingQueryString:@"key2=value2&key3=value3"] query] should]
             equal:@"key=value&key2=value2&key3=value3"];
        });
    });
});

SPEC_END
Run Code Online (Sandbox Code Playgroud)

Sal*_*lmo 72

iOS 7开始,您可以使用非常简单易用的NSURLComponents.看看这些例子:

例1

NSString *urlString = @"https://mail.google.com/mail/u/0/?shva=1#inbox";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];

NSLog(@"%@ - %@ - %@ - %@", components.scheme, components.host, components.query, components.fragment);
Run Code Online (Sandbox Code Playgroud)

例2

NSString *urlString = @"https://mail.google.com/mail/u/0/?shva=1#inbox";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];

if (components) {
    //good URL
} else {
    //bad URL
}
Run Code Online (Sandbox Code Playgroud)

例3

NSURLComponents *components = [NSURLComponents new];
[components setScheme:@"https"];
[components setHost:@"mail.google.com"];
[components setQuery:@"shva=1"];
[components setFragment:@"inbox"];
[components setPath:@"/mail/u/0/"];

[self.webview loadRequest:[[NSURLRequest alloc] initWithURL:[components URL]]];
Run Code Online (Sandbox Code Playgroud)

但是你可以用NSURLComponents做很多其他的事情来看看Apple文档或这个链接上的NSURLComponents类引用:http://nshipster.com/nsurl/


ma1*_*w28 43

这是一个通过您的规范的实现:

@implementation NSURL (Additions)

- (NSURL *)URLByAppendingQueryString:(NSString *)queryString {
    if (![queryString length]) {
        return self;
    }

    NSString *URLString = [[NSString alloc] initWithFormat:@"%@%@%@", [self absoluteString],
                           [self query] ? @"&" : @"?", queryString];
    NSURL *theURL = [NSURL URLWithString:URLString];
    [URLString release];
    return theURL;
}

@end
Run Code Online (Sandbox Code Playgroud)

这是一个实现NSString:

@implementation NSString (Additions)

- (NSURL *)URLByAppendingQueryString:(NSString *)queryString {
    if (![queryString length]) {
        return [NSURL URLWithString:self];
    }

    NSString *URLString = [[NSString alloc] initWithFormat:@"%@%@%@", self,
                           [self rangeOfString:@"?"].length > 0 ? @"&" : @"?", queryString];
    NSURL *theURL = [NSURL URLWithString:URLString];
    [URLString release];
    return theURL;
}

// Or:

- (NSString *)URLStringByAppendingQueryString:(NSString *)queryString {
    if (![queryString length]) {
        return self;
    }
    return [NSString stringWithFormat:@"%@%@%@", self,
            [self rangeOfString:@"?"].length > 0 ? @"&" : @"?", queryString];
}

@end
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,但为了完全安全,你应该在构建URLString时使用[queryString stringByAddingPercentEscapesUsingEncoding:],否则在queryString尚未"url friendly"的情况下你会得到结果URL的nil(例如,当参数值有一个空间). (4认同)

Pet*_*isu 23

iOS8 +现代方式

添加(或替换'ref'值,如果存在)ref = impm到min60.com上的url

if ([[url host] hasSuffix:@"min60.com"]) {

    NSURLComponents *components = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
    NSURLQueryItem * newQueryItem = [[NSURLQueryItem alloc] initWithName:@"ref" value:@"impm"];
    NSMutableArray * newQueryItems = [NSMutableArray arrayWithCapacity:[components.queryItems count] + 1];
    for (NSURLQueryItem * qi in components.queryItems) {
        if (![qi.name isEqual:newQueryItem.name]) {
            [newQueryItems addObject:qi];
        }
    }
    [newQueryItems addObject:newQueryItem];
    [components setQueryItems:newQueryItems];

    url = [components URL];
}
Run Code Online (Sandbox Code Playgroud)


Sob*_*man 8

对于那些不想在构建NSURL时编写样板代码的人来说,这只是一个友好的帖子NSURLComponents.
从iOS8开始,我们就NSURLQueryItem可以帮助您快速构建URL请求.

我写了一个方便的类别来简化工作,你可以在这里抓住:URLQueryBuilder
这是一个使用它是多么容易的例子:

NSString *baseURL = @"https://google.com/search";
NSDictionary *items = @{
    @"q"  : @"arsenkin.com",
    @"hl" : @"en_US",
    @"lr" : @"lang_en"
};

NSURL *URL = [NSURL ars_queryWithString:baseURL queryElements:items];  
// https://google.com/search?q=arsenkin.com&hl=en_US&lr=lang_en
Run Code Online (Sandbox Code Playgroud)


dre*_*ish 5

如果您正在使用RestKit,它会为NSString提供附加功能.其中之一是:

- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)queryParameters
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:
                                @"limit",@"20", 
                                @"location",@"latitude,longitude",
                                nil];
NSString *pathWithQuery = [@"/api/v1/shops.json" stringByAppendingQueryParameters:shopParams]
Run Code Online (Sandbox Code Playgroud)


sam*_*ize 5

NSURLComponents迅速扩展了该添加查询项:

extension NSURLComponents {

    func appendQueryItem(name name: String, value: String) {
        var queryItems: [NSURLQueryItem] = self.queryItems ?? [NSURLQueryItem]()
        queryItems.append(NSURLQueryItem(name: name, value: value))
        self.queryItems = queryItems
    }

}
Run Code Online (Sandbox Code Playgroud)

要使用,

let components = NSURLComponents(string: urlString)!
components.appendQueryItem(name: "key", value: "value")
Run Code Online (Sandbox Code Playgroud)


小智 3

正如其他人提到的,您可以使用NSURLComponents它来构造 URL。

@implementation NSURL (Additions)

- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)queryParameters
{        
    NSURLComponents *components = [[NSURLComponents alloc] initWithURL:self resolvingAgainstBaseURL:NO];
    NSMutableArray *queryItems = [NSMutableArray array:components.queryItems];
    for (NSString *key in [queryParameters allKeys]) {
        NSURLQueryItem *queryItem = [[NSURLQueryItem alloc] initWithName:key value:queryParameters[key]];
        [queryItems addObject:queryItem];
    }
    components.queryItems = queryItems;
    return [components URL];
}

@end
Run Code Online (Sandbox Code Playgroud)