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

前端 未结 16 1053
广开言路
广开言路 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 19:04

    edit (June 2018): this answer is better. Apple added NSURLComponents in iOS 7.

    I would create a dictionary, get an array of the key/value pairs with

    NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
    NSArray *urlComponents = [urlString componentsSeparatedByString:@"&"];
    

    Then populate the dictionary :

    for (NSString *keyValuePair in urlComponents)
    {
        NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
        NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
        NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
    
        [queryStringDictionary setObject:value forKey:key];
    }
    

    You can then query with

    [queryStringDictionary objectForKey:@"ad_eurl"];
    

    This is untested, and you should probably do some more error tests.

提交回复
热议问题