Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error logging into Instagram in iOS app using UIWebView

I'm following Instagram authentication [recommended] steps using UIWebView on an iOS app. After entering credentials, hitting login loads a page with following error.

This page could not be loaded. If you have cookies disabled in your browser, or you are browsing in private mode, please try enabling cookies or turning off private mode, and then retrying your action.

And, this only happens on first run through the steps of authentication; on the next attempt, everything works smooth as silk. I get the code suffixed to redirect url and I request access token using it.

Screenshot:

enter image description here

There's already another question here and it doesn't help.

EDIT: It seems like Cookies issue. Though, I haven't been able to fix it yet.

like image 987
Ajith R Nayak Avatar asked Jun 06 '16 15:06

Ajith R Nayak


2 Answers

I had a similar problem when I was deleting cookies to make sure the log in screen appeared and not just using the currently logged in user. Try (swift):

let storage = HTTPCookieStorage.shared
storage.cookieAcceptPolicy = .always
like image 171
AndyRyan Avatar answered Sep 23 '22 15:09

AndyRyan


I managed to solve this problem about an hour ago.

First, DON'T use UIWebView or WebView; use a WKWebView instead.

You see, you need to implement the method

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error

when instagram's login page forwards you to your redirect_url , it FAILS to navigate. Probably because we're not doing the server-side auth, but only the client-side auth, and the redirect_url is not a valid url. We're expecting the page to REDIRECT to an invalid url, but when that happens, the WKWebView doesn't call the method

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation

or the method

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

So. What you need to do is focus on that first method, check the error variable, and extract error.userInfo.

In my case, this is how I solved the problem:

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
   
    NSURL *err = [error.userInfo objectForKey:@"NSErrorFailingURLKey"];

    if([err.absoluteString hasPrefix:INSTA_REDIRECT_URL]){
        NSString *token = [[err.absoluteString componentsSeparatedByString:@"#access_token="] objectAtIndex:1];
        
     
        [Utils saveToken:token];
        [self.webView setHidden:YES];
        //open next view controller
    }else{
        //TODO: No internet? something else went wrong..
        
        NSLog(@"Error: %@", error);
    }
    
}

Hope it helps. Best of luck! ;)

like image 30
Flávio Marques Avatar answered Sep 22 '22 15:09

Flávio Marques