2012-06-09 102 views
0

的網址是:http://oauth.vk.com/blank.html#access_token=244832666b8168a3mna06f03f5324789a8022455245532b032375f193ceab923&expires_in=86400&user_id=191742解析URL可可

如何解析它在可可和獲得access_tokenuser_id

回答

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 

所以你的URL的sy_keysAndValuesOfFragment會導致這樣的:

{ 
    "access_token" = 244832666b8168a3mna06f03f5324789a8022455245532b032375f193ceab923; 
    "expires_in" = 86400; 
    "user_id" = 191742; 
} 
+0

+1,只是不要忘了使用'進行URL解碼鍵和值 - [的NSString stringByReplacingPercentEscapesUsingEncoding:]' –

+0

@ DaveDeLong感謝您的評論!我真的忘記了這一點,但是因爲我在OP中使用解析器([_a-z0-9] = [_ a-z0-9]),所以編碼不是問題。 –