我正在构建一个iPhone应用程序,它只是现有移动网站的UIWebView
,具有基于表单的登录。当我在iPhone Safari上登录移动网站时,系统会提示我保存用户名/密码,然后当我稍后返回该网站时自动填充。
我想在UIWebView
中启用相同的功能,但对于我的生活,我无法弄清楚如何做到这一点。有什么想法吗?
按照Michael的基本模型(参见接受的答案),我能够完成这项工作。这是我做的:
设置数据
- (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"
答案 0 :(得分:4)
从我看来,我认为没有一种简单的方法可以做到这一点。以下是可能的工作原理: