Как автоматически заполнить имя пользователя и пароль в приложении UIWebView для iOS?

Я учу себя программировать приложение для iPhone, просматривая примеры кода из различных онлайн-источников, поэтому справедливо сказать, что я не понимаю язык (пока).

Я успешно создал приложение браузера UIWebView, которое переходит на страницу входа. Тем не менее, я пытаюсь сделать еще один шаг вперед, имея

Следуя коду Байрона в его собственном вопросе о переполнении стека, я попытался пойти по его стопам.

Возможно ли UIWebView для сохранения и автозаполнения ранее введенных значений формы (например, имени пользователя и пароля)?

Однако, когда следующая строка кода активна в приложении, браузер загрузит только пустую страницу.

    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {

Я очень ценю любую помощь, которая поможет мне вернуться на правильный путь. Большое Вам спасибо,

Ниже приведен весь мой код:



    #import "ViewController.h"

    // 6/13/2012 added to cache username and password
    #import 
    #import "SFHFKeychainUtils.h"
     // -----


    @interface ViewController ()

    @end


    @implementation ViewController
    @synthesize webView;
    @synthesize spinner;

    -(IBAction)goBack:(id)sender{
        if ([webView canGoBack]) {
            [webView goBack];
        }
    }
    -(IBAction)goForward:(id)sender{
        if ([webView canGoForward]){
            [webView goForward];
        }

    }


    - (void)viewDidLoad
    {
        NSURL *url = [NSURL URLWithString:@"http://xxxxxx.com/weblink/hh_login.html"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

    }

    // 6/13/2012 added to cache username and password
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request        navigationType:(UIWebViewNavigationType)navigationType; {

        //save form data
        if(navigationType == UIWebViewNavigationTypeFormSubmitted) {

            //grab the data from the page
            NSString *username = [self.webView stringByEvaluatingJavaScriptFromString: @"document.myForm.username.value"];
            NSString *password = [self.webView stringByEvaluatingJavaScriptFromString: @"document.myForm.password.value"];

            //store values locally
            [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
            [SFHFKeychainUtils storeUsername:username andPassword:password     forServiceName:@"MyService" updateExisting:YES error:nil];

        }    

    }
    // -----


    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:         (UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }

    - (void)webViewDidStartLoad:(UIWebView *)webView {
        [spinner startAnimating];
    }

    //- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //    [spinner stopAnimating];
    //}

    // 6/13/2012 added to cache username and password
    - (void)webViewDidFinishLoad:(UIWebView *)webView{
        [spinner stopAnimating];

        //verify view is on the login page of the site (simplified)
        NSURL *requestURL = [self.webView.request URL];
        if ([requestURL.host isEqualToString:@"http://xxxxxx.com/weblink/hh_login.html"]) {

            //check for stored login credentials
            NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];

            if (username.length != 0 ) {

                //create js strings
                NSString *loadUsernameJS = [NSString     stringWithFormat:@"document.myForm.username.value ='%@'", username];
                NSString *password = [SFHFKeychainUtils getPasswordForUsername: username andServiceName:@"MyService" error:nil];
                if (password.length == 0 ) password = @"";
                NSString *loadPasswordJS = [NSString stringWithFormat:@"document.myForm.password.value ='%@'", password];

                //autofill the form
                [self.webView stringByEvaluatingJavaScriptFromString: loadUsernameJS];
                [self.webView stringByEvaluatingJavaScriptFromString: loadPasswordJS];

            }
        }   
    }
    // -----

    @end


person James Flanagan    schedule 18.06.2012    source источник


Ответы (1)


ПОПРОБУЙТЕ МЕНЬШЕ ОДНОЙ

Вам нужно заполнить учетные данные, когда веб-просмотр загрузится. ниже приведен метод делегата UIWebView, вызываемый при загрузке WebView. В настоящее время передайте учетные данные не так, как они передавались перед загрузкой UIWebView, что неверно.

 - (void)webViewDidFinishLoad:(UIWebView *)webView
    {

    if(!isLoggedIn){//just load only onetime.

      //pass the login Credintails into textfield of WebView. 

    NSString* userId   =  @"userName" //here just replace that string to the username
    NSString* password =   @"password";//here just replace that string to the password


     if(userId != nil && password != nil ){

    NSString*  jScriptString1 = [NSString  stringWithFormat:@"document.getElementById('username').value='%@'", userId];
    //username is the id for username field in Login form

    NSString*  jScriptString2 = [NSString stringWithFormat:@"document.getElementById('password').value='%@'", password];
       //here password is the id for password field in Login Form
     //Now Call The Javascript for entring these Credential in login Form
    [webView stringByEvaluatingJavaScriptFromString:jScriptString1];

    [webView stringByEvaluatingJavaScriptFromString:jScriptString2];
      //Further if you want to submit login Form Automatically the you may use below line    

    [webView stringByEvaluatingJavaScriptFromString:@"document.forms['login_form'].submit();"];
    // here 'login_form' is the id name of LoginForm

    }

    isLoggedIn=TRUE;

}
}

Это действительно поможет вам.

person Kamar Shad    schedule 12.10.2012
comment
У меня только один вопрос... Я создал isLoggedIn как свойство BOOL, например: @property (nonatomic, assign) BOOL isLoggedIn;... форма не принимает пользователя и pW, если я не удалю isLoggedIn... Но я очень хочу его использовать! Помощь ; ) - person Morkrom; 31.05.2013