iOS 獲取URL中的參數

在開發中經常遇到通過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;

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容