Objective-C-格式化GET请求

Objective-C-格式化GET请求,objective-c,nsurlconnection,Objective C,Nsurlconnection,在GET请求url中传递字符串参数(如%JOHN%)的规则是什么 我的请求url应该如下所示: 试试看#1:是我干的 NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%%%@%%",SEARCH_KEYWORD]]; O/p:nil 试试#2: **O/p: https://somesite.com/search/name?name=JOE

在GET请求url中传递字符串参数(如%JOHN%)的规则是什么

我的请求url应该如下所示:

试试看#1:是我干的

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%%%@%%",SEARCH_KEYWORD]];
O/p:nil

试试#2:

**O/p:

https://somesite.com/search/name?name=JOE

有什么建议吗?

您可以使用
NSURLComponents
构建URL:

目标C:

NSURLComponents *components = [NSURLComponents componentsWithString:@"https://google.com"];
components.query = @"s=%search keywords%"

NSURL *url = components.URL;
Swift(在制作过程中小心使用
,我曾经在操场上测试):


另外,如果您需要更复杂的查询,请使用
NSURLComponent
queryItems
属性。

如果您犯了错误,只需使用一个
%@
。 例如:

NSString *string = @"JOE";
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%@",string]]; 
let components = NSURLComponents(string: "https://google.com")!
components = "s=%search keywords%"

let url = components!
print(url) // "https://google.com?s=%25search%20keywords%25"
NSString *string = @"JOE";
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%@",string]];