修改某个参数值
c 方法
NSString *updateQuery(NSString *url, NSString *key, NSString *value)
{
if (isBlankString(url)) {
return @"";
}
NSURLComponents *components = [NSURLComponents componentsWithString:url];
NSMutableArray *tmpQueryItems = [NSMutableArray arrayWithArray:components.queryItems];
[tmpQueryItems enumerateObjectsUsingBlock:^(NSURLQueryItem *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj.name isEqualToString:key]) {
NSURLQueryItem *tmpQueryItem = [[NSURLQueryItem alloc] initWithName:key value:value];
[tmpQueryItems replaceObjectAtIndex:idx withObject:tmpQueryItem];
}
}];
components.queryItems = tmpQueryItems;
return components.string;
}
object-c 方法
- (NSString *)updateUrl:(NSString *)url
key:(NSString *)key
value:(NSString *)value
{
NSURLComponents *components = [NSURLComponents componentsWithString:url];
NSMutableArray *tmpQueryItems = [NSMutableArray arrayWithArray:components.queryItems];
[tmpQueryItems enumerateObjectsUsingBlock:^(NSURLQueryItem *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj.name isEqualToString:key]) {
NSURLQueryItem *tmpQueryItem = [[NSURLQueryItem alloc] initWithName:key value:value];
[tmpQueryItems replaceObjectAtIndex:idx withObject:tmpQueryItem];
}
}];
components.queryItems = tmpQueryItems;
return components.string;
}
给URL 添加多个参数
- (NSURL *)appendUrl:(NSString *)url parameters:(NSDictionary *)parameter
{
NSURLComponents *components = [[NSURLComponents alloc] initWithString:url];
NSMutableArray *array = [NSMutableArray arrayWithArray:components.queryItems];
[parameter.allKeys enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSURLQueryItem *item = [[NSURLQueryItem alloc] initWithName:obj value:parameter[obj]];
[array addObject:item];
}];
components.queryItems = array;
return components.URL;
}