ios - foursquare访问令牌没有来

时间:2013-03-09 12:36:09

标签: ios

我遵循foursquare身份验证指南,但我仍有问题

这是我的代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webView.delegate = self;
    NSString *clientID = @"XXX";
    NSString *redirectURI = @"http://www.example.com";
    NSString *authenticateURLString = [NSString stringWithFormat:@"https://foursquare.com/oauth2/authenticate?client_id=%@&response_type=token&redirect_uri=%@", clientID, redirectURI];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:authenticateURLString]];
    [self.webView loadRequest:request];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([request.URL.scheme isEqualToString:@"itms-apps"]) {
        [[UIApplication sharedApplication] openURL:request.URL];
        return NO;
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *URLString = [[self.webView.request URL] absoluteString];
    NSLog(@"--> %@", URLString);
    if ([URLString rangeOfString:@"access_token="].location != NSNotFound) {
        NSString *accessToken = [[URLString componentsSeparatedByString:@"="] lastObject];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:accessToken forKey:@"access_token"];
        [defaults synchronize];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

但NSLog的输出仅为http://www.example.com。它没有访问令牌返回。我做错了吗?

我在桌面谷歌浏览器中打开此链接,访问令牌成功返回。 (www.example.com#=的access_token XXX) 但是我在iPhone模拟器的游戏中打开了这个链接,它只返回了网址。

感谢您的帮助。

@nearonline

1 个答案:

答案 0 :(得分:1)

我遇到同样的问题,原因是webViewDidFinishLoading中的URL不包含访问令牌。但是shouldStartLoadWithRequest中的URL会。因此,您应该将代码修改为:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *URLString = [[request URL] absoluteString];
    if ([URLString rangeOfString:@"access_token="].location != NSNotFound) {
        NSString *accessToken = [[URLString componentsSeparatedByString:@"="] lastObject];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:accessToken forKey:@"access_token"];
        [defaults synchronize];
        [self dismissViewControllerAnimated:YES completion:nil];
        return NO;
    }
    return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {

}