我正在构建一个 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 钥匙串。
为了让 SFHFKeychainUtils 工作,你需要做一些事情:
- 添加
SFHFKeychainUtils.h
和SFHFKeychainUtils.m
到您的项目 - 添加
Security.framework
到您的项目中 #import <Security/Security.h>
和#import "SFHFKeychainUtils.h"