在Objective-C中,从NSDictionary对象创建URL查询参数可以通过以下步骤实现:
- 导入Foundation框架#import<Foundation/Foundation.h>
- 创建一个NSDictionary对象,包含要作为URL查询参数的键值对NSDictionary *params = @{
@"key1": @"value1",
@"key2": @"value2",
@"key3": @"value3"
};
- 使用NSCharacterSet对象创建一个URL查询参数字符串NSString *query = [self queryStringFromParameters:params];
- 将查询参数字符串附加到URL上NSURL *url = [NSURL URLWithString:@"https://example.com"];
NSURL *urlWithQuery = [NSURL URLWithString:[url absoluteString] relativeToURL:url];
- 完整的代码如下:#import<Foundation/Foundation.h>
@interface NSDictionary (URLQuery)
- (NSString *)queryString;
@end
@implementation NSDictionary (URLQuery)
- (NSString *)queryString {
NSMutableArray *parts = [NSMutableArray array];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *part = [NSString stringWithFormat:@"%@=%@", [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]], [obj stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
[parts addObject:part];
}];
return [parts componentsJoinedByString:@"&"];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDictionary *params = @{
@"key1": @"value1",
@"key2": @"value2",
@"key3": @"value3"
};
NSURL *url = [NSURL URLWithString:@"https://example.com"];
NSURL *urlWithQuery = [NSURL URLWithString:[url absoluteString] relativeToURL:url];
NSString *query = [params queryString];
NSURL *finalURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", [urlWithQuery absoluteString], query]];
NSLog(@"%@", finalURL);
}
return 0;
}
这段代码将创建一个包含查询参数的URL,例如:https://example.com?key1=value1&key2=value2&key3=value3
。