问题
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