获取链接中各个参数值
//获取链接中各个参数值
- (NSDictionary *)getParamsWithUrlString:(NSString *)urlString
{
if (urlString.length == 0) {
NSLog(@"链接为空!");
return @{};
}
//先截取问号
NSArray * allElements = [urlString componentsSeparatedByString:@"?"];
NSMutableDictionary * params = [NSMutableDictionary dictionary];
if (allElements.count == 2) {
//有参数或者?后面为空
NSString * paramString = allElements[1];
//获取参数对
NSArray * paramsArray = [paramString componentsSeparatedByString:@"&"];
if (paramsArray.count >= 2) {
for (NSInteger i = 0; i<paramsArray.count; i++) {
NSString * singleParamString = paramsArray[i];
NSArray * singleParamSet = [singleParamString componentsSeparatedByString:@"="];
if (singleParamSet.count == 2) {
NSString * key = singleParamSet[0];
NSString * value = singleParamSet[1];
if (key.length > 0 || value.length > 0) {
[params setObject:value.length > 0 ? value:@"" forKey:key.length > 0 ? key:@""];
}
}
}
}else if (paramsArray.count == 1){ //无& url只有?后一个参数
NSString * singleParamString = paramsArray[0];
NSArray * singleParamSet = [singleParamString componentsSeparatedByString:@"="];
if (singleParamSet.count == 2) {
NSString * key = singleParamSet[0];
NSString * value = singleParamSet[1];
if (key.length > 0 || value.length > 0) {
[params setObject:value.length > 0 ? value:@"" forKey:key.length > 0 ? key:@""];
}
}else{
//问号后面什么都没有 xxxx? 无需处理
}
}
//整合url及参数
return [params copy];
}else if (allElements.count > 2){
NSLog(@"链接不合法!链接包含多个?");
return @{};
}else{
NSLog(@"链接不包含参数!");
return @{};
}
}
使用:
NSString * url = @"https://www.aaa.com/?key1=value1&key2=value2";
NSDictionary * dic = [self getParamsWithUrlString:url];