- 项目开发中需要截取URL中的参数
http://example.com?param1=value1¶m2=param2
- 直接使用字符串分割
// Swift代码,IOS8以上
extension String {
/// 从String中截取出参数
var urlParameters: [String: AnyObject]? {
// 判断是否有参数
guard let start = self.rangeOfString("?") else {
return nil
}
var params = [String: AnyObject]()
// 截取参数
let index = start.startIndex.advancedBy(1)
let paramsString = substringFromIndex(index)
// 判断参数是单个参数还是多个参数
if paramsString.containsString("&") {
// 多个参数,分割参数
let urlComponents = paramsString.componentsSeparatedByString("&")
// 遍历参数
for keyValuePair in urlComponents {
// 生成Key/Value
let pairComponents = keyValuePair.componentsSeparatedByString("=")
let key = pairComponents.first?.stringByRemovingPercentEncoding
let value = pairComponents.last?.stringByRemovingPercentEncoding
// 判断参数是否是数组
if let key = key, value = value {
// 已存在的值,生成数组
if let existValue = params[key] {
if var existValue = existValue as? [AnyObject] {
existValue.append(value)
} else {
params[key] = [existValue, value]
}
} else {
params[key] = value
}
}
}
} else {
// 单个参数
let pairComponents = paramsString.componentsSeparatedByString("=")
// 判断是否有值
if pairComponents.count == 1 {
return nil
}
let key = pairComponents.first?.stringByRemovingPercentEncoding
let value = pairComponents.last?.stringByRemovingPercentEncoding
if let key = key, value = value {
params[key] = value
}
}
return params
}
}
// Objective-C IOS8以上
@implementation NSString (Utils)
/**
* 截取URL中的参数
*
* @return NSMutableDictionary parameters
*/
- (NSMutableDictionary *)getURLParameters {
// 查找参数
NSRange range = [self rangeOfString:@"?"];
if (range.location == NSNotFound) {
return nil;
}
NSMutableDictionary *params = [NSMutableDictionary dictionary];
// 截取参数
NSString *parametersString = [self substringFromIndex:range.location + 1];
// 判断参数是单个参数还是多个参数
if ([parametersString containsString:@"&"]) {
// 多个参数,分割参数
NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
for (NSString *keyValuePair in urlComponents) {
// 生成Key/Value
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
// Key不能为nil
if (key == nil || value == nil) {
continue;
}
id existValue = [params valueForKey:key];
if (existValue != nil) {
// 已存在的值,生成数组
if ([existValue isKindOfClass:[NSArray class]]) {
// 已存在的值生成数组
NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
[items addObject:value];
[params setValue:items forKey:key];
} else {
// 非数组
[params setValue:@[existValue, value] forKey:key];
}
} else {
// 设置值
[params setValue:value forKey:key];
}
}
} else {
// 单个参数
// 生成Key/Value
NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
// 只有一个参数,没有值
if (pairComponents.count == 1) {
return nil;
}
// 分隔值
NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
// Key不能为nil
if (key == nil || value == nil) {
return nil;
}
// 设置值
[params setValue:value forKey:key];
}
return params;
}
@end
- 使用案例:
// Swift
let url = "http://example.com?param1=value1¶m2=value2"
let url1 = "http://example.com?param1=value1¶m1=value2"
let params = url.urlParameters
let params1 = url1.urlParameters
// 字典
print(params)
// 数组
print(params1)
Optional([“param1”: value1, “param2”: value2])
Optional([“param1”: ( value1, value2 ) ])
Objective-C
NSString *url = @"http://example.com?param1=value1¶m2=value2";
NSString *url1 = @"http://example.com?param1=value1¶m1=value2";
NSDictionary *dic = [url getURLParameters];
NSDictionary *dic1 = [url1 getURLParameters];
NSLog(@"dic ---- \n%@", dic);
NSLog(@"dic1 ---- \n%@", dic1);
2016-08-18 14:14:05.943 test[8591:784432] dic ----
{
param1 = value1;
param2 = value2;
}
2016-08-18 14:15:05.210 test[8625:788127] dic1 ----
{
param1 = (
value1,
value2
);
}
- 另一种方法则是使用系统的类 NSURLComponents
// Swift
let url = "http://example.com?param1=value1¶m2=value2"
let urlComponents = NSURLComponents(string: url)
let queryItems = urlComponents?.queryItems
for item in queryItems! {
print(item.name)
print(item.value)
}
以下方法和上面的截取方法一样,会更简洁:
// Swift代码,IOS8以上
extension String {
/// 从String中截取出参数
var urlParameters: [String: AnyObject]? {
// 截取是否有参数
guard let urlComponents = NSURLComponents(string: self), queryItems = urlComponents.queryItems else {
return nil
}
// 参数字典
var parameters = [String: AnyObject]()
// 遍历参数
queryItems.forEach({ (item) in
// 判断参数是否是数组
if let existValue = parameters[item.name], value = item.value {
// 已存在的值,生成数组
if var existValue = existValue as? [AnyObject] {
existValue.append(value)
} else {
parameters[item.name] = [existValue, value]
}
} else {
parameters[item.name] = item.value
}
})
return parameters
}
}
待续