gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:30:52 42 4
gpt4 key购买 nike

假设我有一个 NSURL?不管它是否已经有一个空的查询字符串,我如何在 NSURLquery 中添加一个或多个参数?也就是说,有人知道这个函数的实现吗?

- (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

最佳答案

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

示例 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
}

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

但是您可以使用 NSURLComponents 做许多其他事情,请查看 Apple 文档或此链接上的 NSURLComponents 类引用:http://nshipster.com/nsurl/

关于Objective-C:如何向 NSURL 添加查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6309698/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com