iOS url请求参数解析

方法一:手动字符串解析

@implementation NSURL(QueryDictionary)

- (NSDictionary*)fm_QueryDictionary {
    NSMutableDictionary *mute = [[NSMutableDictionary alloc] init];
    for (NSString *query in [self.query componentsSeparatedByString:@"&"]) {
        NSArray *components = [query componentsSeparatedByString:@"="];
        if (components.count == 0) {
            continue;
        }
        NSString *key = [components[0] stringByRemovingPercentEncoding];
        id value = nil;
        if (components.count == 1) {
            // key with no value
            value = [NSNull null];
        }
        if (components.count == 2) {
            value = [components[1] stringByRemovingPercentEncoding];
            // cover case where there is a separator, but no actual value
            value = [value length] ? value : [NSNull null];
        }
        if (components.count > 2) {
            // invalid - ignore this pair. is this best, though?
            continue;
        }
        mute[key] = value ?: [NSNull null];
    }
    return mute.count ? mute.copy : nil;
}

@end


方法二:利用NSURL属性

// 参数解析 -- 非纯数字可以解析
NSURL *url = [NSURL URLWithString:strResult];
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];

// url中参数的key value
NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
for (NSURLQueryItem *item in urlComponents.queryItems) {
    [parameter setValue:item.value forKey:item.name];
}

你可能感兴趣的:(iOS url请求参数解析)