Search code examples
iosobjective-cios5authenticationuiwebview

How to detect when a user logged in via a UIWebView?


I want to have present a UIWebView with a login screen for a user to login to a service, and once they are properly logged in, I want to scrape the page for content. How do I figure out when they logged in to the service?

I know I could check the current URL, as it redirects to a specific, easy to identify URL, but at the same time, if they somehow navigated around the web until they came across this link and clicked on it, it would have unexpected results in my app.


Solution

  • There are many ways to send request to the server, you could use some open APIs like ASIHTTPRequest (might be outdated) and AFNetworking. If you want to use Apple provided API then you can use NSURLConnection. Basically you send synchronous request in your case.

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    NSString *reply = [[NSString alloc]  initWithBytes:[data bytes] length:[data length] encoding: NSUTF8StringEncoding];
    

    check the response from the server if user is logged in then open the UIWebView with desired contents otherwise show error or alert.

    if([reply isEqualToString:@"OK"]){
     // open and show Contents in `UIWebView`
    } else {
     //show error not authenticated
    }
    

    Here is some basic tutorial if you getting started.

    One more tutorial for NSURLConnection