Search code examples
iosgtm-oauth2

how to pre-fill email field in GTMOAuth2ViewControllerTouch view


how to pre-fill email field in GTMOAuth2ViewControllerTouch view ?

Is it possible ? Has any one tried this ?

I am using the standard way to create the view controller class and showing the gtm view modally

self.gtmVC = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:googleAuth authorizationURL:[GTMOAuth2SignIn googleAuthorizationURL] keychainItemName:kKeychainItemName delegate:self finishedSelector:@selector(viewController:finishedWithAuth:error:)];


Solution

  • There's no supported way of doing this. However, using Javascript, you can get it done. Here's some steps / code:

    Wait for the Webview Loading to Complete

    GTMOAuth2ViewControllerTouch defines a NSNotification that you can observe through the NSNotificationCenter. It's kGTMOAuth2WebViewStoppedLoading:

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(authControllerWebViewStoppedLoading:)
     name:kGTMOAuth2WebViewStoppedLoading
     object:nil];
    

    The NSNotification object's userInfo dictionary will have a reference to the webview in it. GTMOAuth2ViewControllerTouch also allows public access to the webview. I used the latter in my app.

    Use Javascript to Change the Email Input Entity

    First, you should know that you can get the HTML of the page the webview is showing like so:

    NSString *html = [self.authController.webView
                      stringByEvaluatingJavaScriptFromString:
                      @"document.body.innerHTML"];
    

    You don't need it for this solution, but it will allow you to confirm that the HTML for the Email input entity still looks like the following:

    <input id="Email" name="Email" type="email" 
          placeholder="Email" value="" spellcheck="false" class="">
    

    Once you know that email input entity, you can then use javascript to change its text value:

    - (void)authControllerWebViewStoppedLoading:(NSNotification *)notification
    {
        // Assume emailAddress is a property that holds the email address you
        // you want to pre-populate the Email entity with....
    
        NSString *javascript = [NSString stringWithFormat:
                                @"var elem = document.getElementById(\"Email\");"
                                @"elem.value = \"%@\";", self.emailAddress];
        [self.authController.webView
         stringByEvaluatingJavaScriptFromString:javascript];
    }
    

    That's It

    Obviously this solution runs the risk of having Google change things on their end without checking with you first. But, the worst that happens in that case is that the email stops pre-populating and your user has to type it in manually, at least until you can release an update.

    Hope this helps.