0

网址是:http://oauth.vk.com/blank.html#access_token=244832666b8168a3mna06f03f5324789a8022455245532b032375f193ceab923&expires_in=86400&user_id=191742

如何在 Cocoa 中解析它并得到access_tokenand user_id

4

2 回答 2

2

有一种-fragment方法在 .NSURL之后返回字符串#

这是有用的。这是非常基本的,不支持实体(如&),它只是将字符串拆分&然后拆分=

@interface NSURL (SYBasicKeyValueParsing)
- (NSDictionary *)sy_keysAndValuesOfString:(NSString *)string;
- (NSDictionary *)sy_keysAndValuesOfFragment;
- (NSDictionary *)sy_keysAndValuesOfQuery;
@end

@implementation NSURL (SYBasicKeyValueParsing)

- (NSDictionary *)sy_keysAndValuesOfString:(NSString *)string
{
    if (!string) return nil;

    NSMutableDictionary *result = [NSMutableDictionary dictionary];

    for (NSString *pair in [string componentsSeparatedByString:@"&"]) {
        NSArray *keyAndValue = [pair componentsSeparatedByString:@"="];
        if ([keyAndValue count] == 2) {
            [result setObject:[keyAndValue objectAtIndex:1] forKey:[keyAndValue objectAtIndex:0]];
        }
    }
    return [[result copy] autorelease];
}

- (NSDictionary *)sy_keysAndValuesOfFragment
{
    return [self sy_keysAndValuesOfString:[self fragment]];
}

- (NSDictionary *)sy_keysAndValuesOfQuery
{
    return [self sy_keysAndValuesOfString:[self query]];
}

@end

因此sy_keysAndValuesOfFragment,您的 URL 将导致以下结果:

{
    "access_token" = 244832666b8168a3mna06f03f5324789a8022455245532b032375f193ceab923;
    "expires_in" = 86400;
    "user_id" = 191742;
}
于 2012-06-09T13:58:49.827 回答
1

有一个解析 URL 的类:NSURL。如果这还不够,您可以使用NSString 类的componentsSeparatedByString方法获取参数。

于 2012-06-09T10:13:56.597 回答