How can I get UIWebView to open Facebook login page in response to the OAuth request on iOS 5 and iOS 6?

后端 未结 5 1304
Happy的楠姐
Happy的楠姐 2020-12-15 13:30

We have:
(1) Facebook API-based web application with Facebook OAuth functionality (“the FB web app”)
(2) UIWebView-based browser on iPad (“the Browser”

5条回答
  •  醉话见心
    2020-12-15 13:59

    Did it!

    It kinda of a hack, but the js facebook sdk login on UiWebView at iOS 6 finally works.

    How it could be done? It is a pure JS + Facebook JS SDK + UIWebView Delegate handling functions solution.

    JS - First step)

    a login button (to connect with facebook) calls this function example, that will trigger Face JS login/oauth dialogs:

    function loginWithFacebookClick(){
    
    FB.login(function(response){
        //normal browsers callback 
    });
    
    }
    

    JS - Second step)

    add a authResponseChange listener every time user loads the webpage ( after FB.init() ) to catch user's connected status:

    FB.Event.subscribe('auth.authResponse.Change', function(response){
    //UIWebView login 'callback' handler
    var auth = response.authResponse;
    if(auth.status == 'connected'){
        //user is connected with facebook! just log him at your webapp
    }
    });
    

    AND with app's UIWebView delegate functions you can handler facebook oauth responses

    Objective C - Third step)

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
    NSString *url = [[request URL] absoluteString];
    
    //when user status == connected (has a access_token at facebook oauth response)
    if([url hasPrefix:@"https://m.facebook.com/dialog/oauth"] && [url rangeOfString:@"access_token="].location != NSNotFound)
    {
        [self backToLastPage];
        return NO;
    }
    
    return YES;
    }
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
    
    NSString *url = [[webView.request URL] absoluteString];
    
    if([url hasPrefix:@"https://m.facebook.com/dialog/oauth"])
    {
        NSString *bodyHTML = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
    
        //Facebook oauth response dead end: is a blank body and a head with a script that does 
        //nothing. But if you got back to your last page, the handler of authResponseChange
        //will catch a connected status if user did his login and auth app
        if([bodyHTML isEqualToString:@""])
        {
            [self backToLastPage];
        }
    }
    
    }
    

    So, when 'redirect' user to the last loaded page, the second step is going to handler user action at facebook login dialogs.

    If I got too fast with this answer, please ask me! Hope it helps.

提交回复
热议问题