URL拼接参数方法
2021-01-12 本文已影响0人
零下十一度
[iOS] --------url拼接参数方法
url拼接参数,判断后面是否有 “?”的情况
NSString+Extention.h
#import <Foundation/Foundation.h>
@interface NSString (Extention)
-(NSString *)urlAddCompnentForValue:(NSString *)value key: (NSString *)key;
@end
NSString+Extention.m
#import "NSString+Extention.h"
@implementation NSString (Extention)
-(NSString *)urlAddCompnentForValue:(NSString *)value key:(NSString *)key{
NSMutableString *string = [[NSMutableString alloc]initWithString:self];
@try {
NSRange range = [string rangeOfString:@"?"];
if (range.location != NSNotFound) {//找到了
//如果?是最后一个直接拼接参数
if (string.length == (range.location + range.length)) {
NSLog(@"最后一个是?");
string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
}else{//如果不是最后一个需要加&
if([string hasSuffix:@"&"]){//如果最后一个是&,直接拼接
string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
}else{//如果最后不是&,需要加&后拼接
string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,value]];
}
}
}else{//没找到
if([string hasSuffix:@"&"]){//如果最后一个是&,去掉&后拼接
string = (NSMutableString *)[string substringToIndex:string.length-1];
}
string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"?%@=%@",key,value]];
}
} @catch (NSException *exception) {
} @finally {
}
return string.copy;
}
@end