在 ObjectiveC 中从 NSDictionary 对象创建 URL 查询参数 [英] Creating URL query parameters from NSDictionary objects in ObjectiveC

查看:30
本文介绍了在 ObjectiveC 中从 NSDictionary 对象创建 URL 查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于标准 Cocoa 库中的所有 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;

我还写了一篇博客文章,介绍如何使用 NSURLComponentsNSURLQueryItems 构建 URL.

I've also written a blog post on how to build URLs with NSURLComponents and NSURLQueryItems.

这篇关于在 ObjectiveC 中从 NSDictionary 对象创建 URL 查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆