Extract token from response string

天涯浪子 提交于 2020-01-06 08:01:46

问题


How to extract token from response string? (I don't know the length of token, so I can't use NSRange here)

oauth_callback_confirmed=true&oauth_token=72157632316931441
-fadcd6ef70cbd06c&oauth_token_secret=a7e7b046a8960559

Current code is(it gives token and rest of the string):

NSRange access_token_range = [operation.responseString rangeOfString:@"oauth_token="];
        if (access_token_range.length > 0) {
            int from_index = access_token_range.location + access_token_range.length;
            NSString *access_token = [operation.responseString substringFromIndex:from_index];

            NSLog(@"access_token:  %@", access_token);
        }

回答1:


It's better (more elegant) to separate the response strings to key-value pairs and then process them separately:

NSString *token = nil;
NSArray *kvpairs = [operation.responseString componentsSeparatedByString:@"&"];
for (NSString *kvpair in kvpairs) {
    NSArray *keyAndValue = [kvpair componentsSeparatedByString:@"="];
    NSString *key = [keyAndValue objectAtIndex:0];
    if ([key isEqualToString:@"oauth_token"]) {
        token = [keyAndValue objectAtIndex:1];
        break;
    }
}

Now token will contain the token or nil if it could not be found.



来源:https://stackoverflow.com/questions/14011385/extract-token-from-response-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!