从ObjectiveC中的NSDictionary对象创建URL查询参数 [英] Creating URL query parameters from NSDictionary objects in ObjectiveC
问题描述
所有URL处理对象都位于标准可可库中(NSURL,NSMutableURL,NSMutableURLRequest等),我知道我必须忽略一种简单的方法来以编程方式编写GET请求.
With all the URL-handling objects lying around in the standard Cocoa libraries (NSURL, NSMutableURL, NSMutableURLRequest, etc), I know I must be overlooking an easy way to programmatically compose a GET request.
目前,我正在手动添加?"紧随其后的是由&"连接的名称值对,但是我的所有名称和值对都需要手动编码,因此NSMutableURLRequest在尝试连接到URL时不会完全失败.
Currently I'm manually appending "?" followed by name value pairs joined by "&", but all of my name and value pairs need to be manually encoded so NSMutableURLRequest doesn't fail entirely when it tries to connect to the URL.
感觉我应该可以使用预烘焙的API来做某事....是否有任何现成的东西可以将NSDictionary查询参数附加到NSURL?我还有其他方法可以解决这个问题吗?
This feels like something I should be able to use a pre-baked API for.... is there anything out of the box to append an NSDictionary of query parameters to an NSURL? Is there another way I should approach this?
推荐答案
在iOS8和OS X 10.10中引入的是NSURLQueryItem
,可用于构建查询.从 NSURLQueryItem 上的文档:
Introduced in iOS8 and OS X 10.10 is NSURLQueryItem
, which can be used to build queries. From the docs on NSURLQueryItem:
NSURLQueryItem对象代表URL的查询部分中项目的单个名称/值对.您可以将查询项与NSURLComponents对象的queryItems属性一起使用.
An NSURLQueryItem object represents a single name/value pair for an item in the query portion of a URL. You use query items with the queryItems property of an NSURLComponents object.
要创建一个,请使用指定的初始化程序queryItemWithName:value:
,然后将它们添加到NSURLComponents
以生成NSURL
.例如:
To create one use the designated initializer queryItemWithName:value:
and then add them to NSURLComponents
to generate an NSURL
. For example:
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://stackoverflow.com"];
NSURLQueryItem *search = [NSURLQueryItem queryItemWithName:@"q" value:@"ios"];
NSURLQueryItem *count = [NSURLQueryItem queryItemWithName:@"count" value:@"10"];
components.queryItems = @[ search, count ];
NSURL *url = components.URL; // http://stackoverflow.com?q=ios&count=10
请注意,问号和&符号是自动处理的.从参数字典创建NSURL
很简单:
Notice that the question mark and ampersand are automatically handled. Creating an NSURL
from a dictionary of parameters is as simple as:
NSDictionary *queryDictionary = @{ @"q": @"ios", @"count": @"10" };
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in queryDictionary) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:key value:queryDictionary[key]]];
}
components.queryItems = queryItems;
我还写了一篇博客文章,其中介绍了如何使用NSURLComponents
和NSURLQueryItems
构建URL.
I've also written a blog post on how to build URLs with NSURLComponents
and NSURLQueryItems
.
这篇关于从ObjectiveC中的NSDictionary对象创建URL查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!