码迷,mamicode.com
首页 > 编程语言 > 详细

将参数字典排序,并转为 GET 参数形式.

时间:2016-03-03 13:06:35      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

1.创建 NSString 分类

@interface NSString (WBRequest)

- (NSString *)URLEncodedString;
- (NSString *)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding;
@end

@implementation NSString (WBRequest)

- (NSString *)URLEncodedString
{
    return [self URLEncodedStringWithCFStringEncoding:kCFStringEncodingUTF8];
}

- (NSString *)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding
{
    return (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[self mutableCopy], NULL, CFSTR("?=,!$&‘()*+;@?\n\"<>#\t :/"), encoding));
}

@end

2.将参数字典排序,并转为 GET 参数形式.

+ (NSString *)stringFromDictionaryWithApi:(NSDictionary *)dict
{
    NSArray *sortArray=[dict allKeys];
    
    NSArray *array =  [sortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableArray *pairs = [NSMutableArray array];
    for (int i =0; i<array.count; i++) {
        NSString * key =[array objectAtIndex:i];
        NSString * value =[dict objectForKey:[array objectAtIndex:i]];
        if ([[dict objectForKey:[array objectAtIndex:i]] isKindOfClass:[NSString class]]) {
            value= [value URLEncodedString];
        }
        [pairs addObject:[NSString stringWithFormat:@"%@=%@",key,value]];
    }
    
    return [pairs componentsJoinedByString:@"&"];
}

 

将参数字典排序,并转为 GET 参数形式.

标签:

原文地址:http://www.cnblogs.com/wzyking/p/5237948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!