Search code examples
iosobjective-coauthnsurl

How to parse value from a url in iOS?


I have a url :

DBSession url : db-qf8erkjgfnhno://1/connect?oauth_token_secret=7ek3fhnfnhla&state=58444830-7764-4DBE-A4F1-84B8604sv2C5&oauth_token=c93dvvaa5b47&uid=2841089

I want to take the value of oauth_token_secret and oauth_token. I tried with [url query] method and get oauth_token_secret=7ek3fhnfnhla&state=58444830-7764-4DBE-A4F1-84B8604sv2C5&oauth_token=c93dvvaa5b47&uid=2841089, but i can not find the method to get the value of oauth_token_secret and oauth_token.

Please help me out.


Solution

  • You can parse query parameters into NSMutableDictionary, and after that retrieve values from there.

    NSString *query = [url query];  
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *param in [query componentsSeparatedByString:@"&"]) {
      NSArray *elts = [param componentsSeparatedByString:@"="];
      if([elts count] < 2) continue;
      [params setObject:[elts objectAtIndex:1] forKey:[elts objectAtIndex:0]];
    }
    NSLog(@"oauth_token_secret : %@", params[@"oauth_token_secret"]);    
    NSLog(@"oauth_token : %@", params[@"oauth_token"]);