- (NSString *)addURLParameter:(NSString *)parameterName withValue:(NSString *)parameterValue {
// 获取 URL 的 query 部分
NSString *query = nil;
NSRange queryRange = [self rangeOfString:@"?" options:NSLiteralSearch];
// 标记是否在原URL中发现了?
BOOL isExistQuestionMark = queryRange.location != NSNotFound;
if (isExistQuestionMark) {
query = [self substringFromIndex:NSMaxRange(queryRange)];
}
//保存目前处理过的参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
if(query){
NSArray *queryComponents = [query componentsSeparatedByString:@"&"];
for(NSString *param in queryComponents){
NSArray *keyValue = [param componentsSeparatedByString:@"="];
if(keyValue.count > 0){
[params setValue:keyValue.count==2?keyValue[1]:@"" forKey:keyValue[0]];
}
}
}
// 将新参数加入到目前处理过的参数中, 如果参数名存在则替换旧的值
[params setValue:parameterValue forKey:parameterName];
// 根据目前处理过的参数,重新生成查询的query
NSMutableString *newQuery = [NSMutableString string];
[params enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if([newQuery length] == 0){
[newQuery appendFormat:@"%@=%@", key,obj];
}else{
[newQuery appendFormat:@"&%@=%@", key,obj];
}
}];
return isExistQuestionMark?[self stringByReplacingOccurrencesOfString:query withString:newQuery]:[NSString stringWithFormat:@"%@?%@",self,newQuery];
}
发表回复