ios url params截取
- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr { NSMutableDictionary *params = [NSMutableDictionary dictionary];// 以字典形式將參數返回 NSString *parametersString = urlStr; NSRange range = [urlStr rangeOfString:@"?"];// 查找參數 if (range.location != NSNotFound) { 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]; if (key == nil || value == nil) {// Key不能爲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]; if (key == nil || value == nil) {// Key不能爲nil return nil; } [params setValue:value forKey:key];// 設置值 } return params; }
歡迎關注本站公眾號,獲取更多信息