引言: 在開發過程中有些時候我們需要得到某些鏈接的參數, 然后根據參數做一些事情。例如我們的需要跟web頁面交互, 可以通過這些參數去做相應的事情。
/**
* 截取URL中的參數
*
* @return NSMutableDictionary parameters
*/
- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
// 查找參數
NSRange range = [urlStr rangeOfString:@"?"];
if (range.location == NSNotFound) {
return nil;
}
// 以字典形式將參數返回
NSMutableDictionary *params = [NSMutableDictionary dictionary];
// 截取參數
NSString *parametersString = [urlStr 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;
}