Objective-C:如何向NSURL添加查询参数? [英] Objective-C: How to add query parameter to NSURL?
本文介绍了Objective-C:如何向NSURL添加查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个NSURL
?它是否已经有一个空的查询字符串,如何在NSURL
的query
中添加一个或多个参数?也就是说,有人知道该功能的实现吗?
Let's say I have an NSURL
? Whether or not it already has an empty query string, how do I add one or more parameters to the query
of the NSURL
? I.e., does anyone know of an implementation of this function?
- (NSURL *)URLByAppendingQueryString:(NSString *)queryString
使其满足此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
推荐答案
以下是通过您的规范的实现:
Here's an implementation that passes your specs:
@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
这是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
这篇关于Objective-C:如何向NSURL添加查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文