我试图通过UIWebView访问一个安全的网站.当我通过safari访问它时,我得到了一个身份验证挑战,但同样的情况并没有出现在应用程序的UIWebView中.我该如何让它出现?
任何指针,示例代码或链接都将非常有用.非常感谢.
这实际上非常简单......我确信你可以在显示auth挑战委托时显示UIAlertView(或者在加载URL之前,如果你确定你正在点击的URL会提示输入身份验证登录信息).无论如何,诀窍是创建自己的NSURLConnection
,我做一些逻辑来保存是否已使用auth委托.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; { NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authed); if (!_authed) { _authed = NO; /* pretty sure i'm leaking here, leave me alone... i just happen to leak sometimes */ [[NSURLConnection alloc] initWithRequest:request delegate:self]; return NO; } return YES; } - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; { NSLog(@"got auth challange"); if ([challenge previousFailureCount] == 0) { _authed = YES; /* SET YOUR credentials, i'm just hard coding them in, tweak as necessary */ [[challenge sender] useCredential:[NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; } } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; { NSLog(@"received response via nsurlconnection"); /** THIS IS WHERE YOU SET MAKE THE NEW REQUEST TO UIWebView, which will use the new saved auth info **/ NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:]]; [_webView loadRequest:urlRequest]; } - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection; { return NO; }
您还可以在网址中提供您的凭据.只需在"http://"和"page url"之间添加用户名和密码即可.
NSString *urlString = @"http://username:password@domain.com/home"; [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];