如何在 UIWebView 中显示身份验证质询? [英] How to display the Authentication Challenge in UIWebView?

查看:24
本文介绍了如何在 UIWebView 中显示身份验证质询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 UIWebView 访问安全网站.当我通过 safari 访问它时,我收到了一个身份验证挑战,但在应用程序的 UIWebView 中没有出现同样的问题.我怎样才能让它出现?

I am trying to access a secure website through UIWebView. When I access it through safari, i get an authentication challenge but the same does not appear in my UIWebView in the application. How can I make it appear?

任何指针、示例代码或链接都会非常有帮助.非常感谢.

Any pointers, sample code or links will be very helpful. Thanks a lot.

推荐答案

这实际上非常简单...我相信您可以在显示验证质询委托时(或在加载 URL 之前,如果您肯定知道您点击的 URL 会提示输入身份验证登录信息).无论如何,诀窍是创建自己的 NSURLConnection 并且我做了一些逻辑来保存是否已使用身份验证委托.

It's actually super easy... I'm sure you can just show a UIAlertView when the auth challenge delegate is shown (or prior to loading the URL, if you know for sure that the URL you're hitting will prompt for auth login info). Anyways, the trick is to create your own NSURLConnection and I do some logic to save whether the auth delegate has been used.

- (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 中显示身份验证质询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆