当前位置:  开发笔记 > 编程语言 > 正文

如何在UIWebView中显示身份验证质询?

如何解决《如何在UIWebView中显示身份验证质询?》经验,为你挑选了2个好方法。

我试图通过UIWebView访问一个安全的网站.当我通过safari访问它时,我得到了一个身份验证挑战,但同样的情况并没有出现在应用程序的UIWebView中.我该如何让它出现?

任何指针,示例代码或链接都将非常有用.非常感谢.



1> Sahil..:

这实际上非常简单......我确信你可以在显示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;
}


不适用于POST.即使是对此的简单修改仍然不适用于POST.
这不适用于任何未经过身份验证的请求(_authed始终== NO并且触发无限循环).即使你修复了这个问题,这仍然无效,因为每个网页多次触发shouldStartLoadWithRequest,最终导致最后一个网页视图加载的网址视图是网页视图中显示的唯一内容.
似乎当连接断开时,auth数据会丢失而`_authed`仍为"YES",并且没有机会再次进行身份验证.

2> 小智..:

您还可以在网址中提供您的凭据.只需在"http://"和"page url"之间添加用户名和密码即可.

NSString *urlString = @"http://username:password@domain.com/home";
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];

推荐阅读
mobiledu2402851173
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有