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

前端 未结 16 1030
广开言路
广开言路 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:56

    I'm a bit late, but the answers provided until now didn't work as I needed to. You can use this code snippet:

    NSMutableDictionary *queryStrings = [[NSMutableDictionary alloc] init];
    for (NSString *qs in [url.query componentsSeparatedByString:@"&"]) {
        // Get the parameter name
        NSString *key = [[qs componentsSeparatedByString:@"="] objectAtIndex:0];
        // Get the parameter value
        NSString *value = [[qs componentsSeparatedByString:@"="] objectAtIndex:1];
        value = [value stringByReplacingOccurrencesOfString:@"+" withString:@" "];
        value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
        queryStrings[key] = value;
    }
    

    Where url is the URL you want to parse. You have all of the query strings, escaped, in the queryStrings mutable dictionary.

    EDIT: Swift version:

    var queryStrings = [String: String]()
    if let query = url.query {
        for qs in query.componentsSeparatedByString("&") {
            // Get the parameter name
            let key = qs.componentsSeparatedByString("=")[0]
            // Get the parameter value
            var value = qs.componentsSeparatedByString("=")[1]
            value = value.stringByReplacingOccurrencesOfString("+", withString: " ")
            value = value.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    
            queryStrings[key] = value
        }
    }
    
    0 讨论(0)
  • 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"]];
    
    0 讨论(0)
  • 2020-11-29 19:00
    -(NSArray *)getDataOfQueryString:(NSString *)url{
        NSArray *strURLParse = [url componentsSeparatedByString:@"?"];
        NSMutableArray *arrQueryStringData = [[NSMutableArray alloc] init];
        if ([strURLParse count] < 2) {
            return arrQueryStringData;
        }
        NSArray *arrQueryString = [[strURLParse objectAtIndex:1] componentsSeparatedByString:@"&"];
    
        for (int i=0; i < [arrQueryString count]; i++) {
            NSMutableDictionary *dicQueryStringElement = [[NSMutableDictionary alloc]init];
            NSArray *arrElement = [[arrQueryString objectAtIndex:i] componentsSeparatedByString:@"="];
            if ([arrElement count] == 2) {
                [dicQueryStringElement setObject:[arrElement objectAtIndex:1] forKey:[arrElement objectAtIndex:0]];
            }
            [arrQueryStringData addObject:dicQueryStringElement];
        }
    
        return arrQueryStringData; 
    }
    

    You this function just Pass URL and you will get all the element of querystring.

    0 讨论(0)
  • 2020-11-29 19:02

    Query property in the NSURL will give the query string. Then you can parse the query string using componentsSeparatedByString

        NSArray *parameters = [[url query] componentsSeparatedByString:@"&"];
    
        NSMutableDictionary *keyValuePairs = [NSMutableDictionary dictionary];
    
        for (NSString *eachParam in parameters)
        {
            NSArray *QryParts = [eachParam componentsSeparatedByString:@"="];
            if ( [QryParts count] == 2 )
            {
                keyValuePairs[QryParts[0]] = QryParts[1];
            }
            else
            {
                keyValuePairs[QryParts[0]] = QryParts[0];
            }
        }
    
    NSString * name = [keyValuePairs valueForKey:@"name"];
    NSString * username = [keyValuePairs valueForKey:@"username"];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 19:05

    Swift 5

    extension URL {
        func queryParams() -> [String:String] {
            let queryItems = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems
            let queryTuples: [(String, String)] = queryItems?.compactMap{
                guard let value = $0.value else { return nil }
                return ($0.name, value)
            } ?? []
            return Dictionary(uniqueKeysWithValues: queryTuples)
        }
    }
    
    0 讨论(0)
提交回复
热议问题