我正在构建一个iPhone应用程序,该应用程序只是具有基于表单的登录名的现有移动网站的UIWebView
。当我在iPhone Safari上登录移动网站时,系统会提示我保存用户名/密码,然后稍后再返回该网站时,该用户名/密码会自动填充。
我想在UIWebView
中启用相同的功能,但是对于我一生来说,我不知道该怎么做。有任何想法吗?
解
遵循迈克尔的基本模型(请参阅公认的答案),我能够完成此工作。这是我所做的:
设定数据
- (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)webViewDidFinishLoad:(UIWebView *)webView{
//verify view is on the login page of the site (simplified)
NSURL *requestURL = [self.webView.request URL];
if ([requestURL.host isEqualToString:@"www.mydomain.com"]) {
//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];
}
}
}
请注意,我正在使用Buzz Andersen很棒的SFHFKeychainUtils包将敏感数据存储到iOs钥匙串(keychain)。为了使SFHFKeychainUtils正常工作,您需要做一些事情:
SFHFKeychainUtils.h
和SFHFKeychainUtils.m
添加到您的项目Security.framework
添加到您的项目中#import <Security/Security.h>
和#import "SFHFKeychainUtils.h"
最佳答案
从我看来,我认为没有简单的方法可以做到这一点。这是一个可能起作用的想法: