0

我正在遵循foursquare authen指南,但我仍然有问题

这是我的代码

- (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 模拟器的 safari 中打开了这个链接,它只返回了 url。

感谢帮助。

@nearonline

4

1 回答 1

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 {

}
于 2013-03-25T03:07:02.723 回答