美文网首页记录的东西
iOS 获取URL中的参数

iOS 获取URL中的参数

作者: YF_0630 | 来源:发表于2019-08-14 15:11 被阅读0次

    在开发中经常遇到通过URL来获取参数,下面总结了几个方法

    通过 NSURLComponents 获取

    
    /**
    
    获取url的所有参数
    
    @param url 需要提取参数的url
    
    @return NSDictionary
    
    */
    
    -(NSDictionary *)paramerWithURL:(NSURL *) url {
    
        NSMutableDictionary *paramer = [[NSMutableDictionary alloc]init];
    
        //创建url组件类
    
        NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
    
        //遍历所有参数,添加入字典
    
        [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
            [paramer setObject:obj.value forKey:obj.name];
    
        }];
    
        return paramer;
    
    }
    
    

    通过 key 来获取 url 中的参数值 未获取到返回空字符串

    
    - (NSString *)getParamByKey:(NSString *)key URLString:(NSString *)url
    
    {
    
        NSError *error;
    
        NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", key];
    
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
    
                                                                              options:NSRegularExpressionCaseInsensitive
    
                                                                                error:&error];
    
        // 执行匹配的过程
    
        NSArray *matches = [regex matchesInString:url
    
                                          options:0
    
                                            range:NSMakeRange(0, [url length])];
    
        for (NSTextCheckingResult *match in matches) {
    
            NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];
    
            return tagValue;
    
        }
    
        return @"";
    
    }
    
    

    也可以通过简单易懂的方法

    
    - (NSMutableDictionary *)parseURLParameters:(NSString *)url{
    
        NSRange range = [url rangeOfString:@"?"];
    
        if (range.location == NSNotFound) return nil;
    
    
    
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    
    
        NSString *parametersString = [url substringFromIndex:range.location + 1];
    
        if ([parametersString containsString:@"&"]) {
    
            NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
    
    
    
            for (NSString *keyValuePair in urlComponents) {
    
                NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
    
                NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
    
                NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
    
    
    
                if (key == nil || value == nil) {
    
                    continue;
    
                }
    
    
    
                id existValue = [parameters valueForKey:key];
    
                if (existValue != nil) {
    
                    if ([existValue isKindOfClass:[NSArray class]]) {
    
                        NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
    
                        [items addObject:value];
    
                        [parameters setValue:items forKey:key];
    
                    } else {
    
                        [parameters setValue:@[existValue, value] forKey:key];
    
                    }
    
                } else {
    
                    [parameters setValue:value forKey:key];
    
                }
    
            }
    
        } else {
    
            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) {
    
                return nil;
    
            }
    
            [parameters setValue:value forKey:key];
    
        }
    
    
    
        return parameters;
    
    }
    
    

    相关文章

      网友评论

        本文标题:iOS 获取URL中的参数

        本文链接:https://www.haomeiwen.com/subject/ztwgjctx.html