Best way to parse URL string to get values for keys?

前端 未结 16 1121
广开言路
广开言路 2020-11-29 18:36

I need to parse a URL string like this one:

&ad_eurl=http://www.youtube.com/video/4bL4FI1Gz6s&hl=it_IT&iv_logging_level=3&ad_flags=0&ends         


        
16条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 18:59

    As full function:

    + (NSString *)getQueryComponentWithName:(NSString *)name  fromURL:(NSURL *)url{
    
    NSString *component = nil;
    if (url) {
        NSString *query = url.query;
    
        NSMutableDictionary *queryStringDictionary = [NSMutableDictionary dictionary];
        NSArray *urlComponents = [query componentsSeparatedByString:@"&"];
    
        for (NSString *keyValuePair in urlComponents){
    
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
            NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
    
            [queryStringDictionary setObject:value forKey:key];
        }
    
        component = [queryStringDictionary objectForKey:name];
    }
    
    return component;
    }
    [self getQueryComponentWithName:@"example" fromURL:[NSURL URLWithString:@"https://google.es/?example=test"]];
    

提交回复
热议问题