如何在UIWebView中显示身份验证挑战?

我试图通过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;
}

如你所知,UIWebView不提供与服务器通信的机会。 我通过这种方式解决了这个问题:在UIWebView的委托方法shouldStartLoadWithRequest中,我使用NSURLConnection启动另一个连接,并且已经在委托NSURLConnection didReceiveAuthenticationChallenge的方法中处理了来自服务器的挑战。 在方法didReceiveResponse(如果挑战来临),然后再次在同一个UIWebView加载相同的URL(挑战已被处理:)。 不要忘记取消didReceiveResponse中的连接,否则会使流量增加一倍。


您也可以在网址中提供您的凭据。 只需在'http://'和'网页网址'之间添加用户名和密码即可。

NSString *urlString = @"http://username:password@domain.com/home";
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
链接地址: http://www.djcxy.com/p/22297.html

上一篇: How to display the Authentication Challenge in UIWebView?

下一篇: HTTP digest authentication fail due to wrong nonce