如何从iOS应用中的Safari网址获取响应数据?

时间:2015-10-08 11:26:22

标签: ios objective-c iphone url safari

我想在Safari中登录Instagram,并希望在ios应用程序中对其进行响应。

我已经从iPhone应用程序重定向到Safari for Instagram登录。 现在我想在iPhone应用程序中获取Safari登录Safari的响应数据。

我不知道。这可能吗?我们可以在iOS应用程序中获得Safari URL的响应吗?

1 个答案:

答案 0 :(得分:1)

为此你必须使用UIWebView及其委托方法。

来自Instagram-Auth-iOS的代码

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *responseURL = [request.URL absoluteString];

    NSString *urlCallbackPrefix = [NSString stringWithFormat:@"%@/?code=", INSTAGRAM_CALLBACK_BASE];

    //We received the code, now request the auth token from Instagram.
    if([responseURL hasPrefix:urlCallbackPrefix])
    {
        NSString *authToken = [responseURL substringFromIndex:[urlCallbackPrefix length]];

        NSURL *url = [NSURL URLWithString:@"https://api.instagram.com/oauth/access_token"];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

        NSDictionary *paramDict = [NSDictionary dictionaryWithObjectsAndKeys:authToken, @"code", INSTAGRAM_CALLBACK_BASE, @"redirect_uri", @"authorization_code", @"grant_type",  INSTAGRAM_CLIENT_ID, @"client_id",  INSTAGRAM_CLIENT_SECRET, @"client_secret", nil];

        NSString *paramString = [paramDict urlEncodedString];

        NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

        [request setHTTPMethod:@"POST"];
        [request addValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@",charset] forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:[paramString dataUsingEncoding:NSUTF8StringEncoding]];

        self.tokenRequestConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

        [self.tokenRequestConnection start];

        return NO;
    }

    return YES;
}

Github上的这个回购Instagram-Auth-iOS将帮助你