2012-01-23 35 views
1

我想跳過一個網站的登錄頁面,這樣我就可以給用戶帶來更加美觀的登錄頁面,並保存它們的登錄憑證在自動登錄未來。到目前爲止,我有兩個UITextFields和一個UIButton。用戶輸入他們的用戶名和密碼,當按下UIButton時,他們的詳細信息將被輸入到網站登錄頁面上的實際網絡表單中,隨後的「登錄」頁面將顯示在UIWebView中。當應用程序記錄用戶時,webView將被隱藏,然後在加載「登錄」頁面時顯示。呼叫在一個UIWebView的HTML web表單「動作」

我已經設法填充webform,但根本無法實際提交它!我確定有一個非常簡單的解決方案!

這是我到目前爲止的代碼,如果有一個更好的辦法我應該做這讓我知道!

-(IBAction)login:(id)sender 
{ 
    // Create js strings  
    NSString *loadUsernameJS = [NSString stringWithFormat:@"var username = document.getElementsByName('username')[0]; username.value='%@';", username.text]; 
    NSString *loadPasswordJS = [NSString stringWithFormat:@"var password = document.getElementsByName('password')[0]; password.value='%@';", password.text];  

    // Autofill the form - this works, and I can see the values being put into the webform 
    [self.webView stringByEvaluatingJavaScriptFromString: loadUsernameJS]; 
    [self.webView stringByEvaluatingJavaScriptFromString: loadPasswordJS]; 

     // This is the method I have tried to submit the form, but nothing happens (ct100 is the ID of the form). 

    [self.webView stringByEvaluatingJavaScriptFromString:@"document.ct100.submit();"]; 

} 

回答

0

嘗試:

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"ct100\").submit()"]; 

您的視圖控制器需要實現UIWebViewDelegate協議,併爲自己設定爲一個UIWebView的delegate。從webView:shouldStartLoadWithRequest返回YES(請參閱下面的代碼)將允許Web視圖導航到表單提交到的任何URL。

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
{ 
    NSLog(@"Allow navigation to request = %@", request); 
    return YES; 
} 
+0

感謝您的回覆Sanjit,遺憾的是仍然沒有運氣!我不知道爲什麼這不起作用。 – Luke

+0

你在你的UIWebViewDelegate實現中實現了webView:shouldStartLoadWithRequest:navigationType:您需要爲指定的請求返回YES才能使Web視圖導航到提交網址。 –

+0

我對這個有點新,你想介紹一下更詳細的介紹,我會如何處理具體的請求? – Luke

1

下面的方法也許對你有幫助

Put this code inside the didFinishLoading Method Of UIWebView Protocol 

填寫的用戶ID

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('username').value = 'userId'"]; 

填寫密碼

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('password').value = 'password'"]; 

呼叫提交按鈕,如下

[webView 
stringByEvaluatingJavaScriptFromString:@"document.forms['login_form'].submit();"]; 

這裏login_form是你的名稱形式

注:必須管理的一件事,一旦你已經填補了憑證點擊提交按鈕。你需要做一些布爾或其他的東西來避免加載UIWebView的重複。