【问题标题】:Issues with UIWebView and HTTP Basic AuthUIWebView 和 HTTP 基本身份验证的问题
【发布时间】:2014-01-09 10:16:09
【问题描述】:

我在网上搜索了如何在 uiwebview 中进行基本的 http 身份验证。我已经尝试了所有方法并且无论我做什么都会得到不一致的结果。有时身份验证有效,有时无效。它把我逼疯了,我很想得到一些帮助!

这是相关代码。我总是遇到身份验证挑战,但 webview 并不总是加载(我基本上超时等待 webViewDidFinishLoad - 没有错误)。有什么想法吗?

/*
 Load a webview
*/
- (void)loadWebView
{
    NSLog(@"loading webview");
    if( _webView == NULL ){
        // UIWebView initialization
        _webView = [[UIWebView alloc] init];
        _webView.hidden = TRUE;
    }

    // set up webview request
    NSURL *url = [NSURL URLWithString:BASE_URL];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:30];

    // load the request
    [_webView setDelegate:self];
    [_webView loadRequest:request];

    // add ourselves as delegate to connection events so we can authenticate
    (void)[NSURLConnection connectionWithRequest:request delegate:self];
}


/**
 authenticates against HTTP basic authorization
 */
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //receive a authenticate and challenge with the user credential
    NSLog(@"got auth challenge.  Authenticating...");
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic] &&
        [challenge previousFailureCount] == 0)
    {
        NSURLCredential *credentail = [NSURLCredential
                                       credentialWithUser:AUTH_USERNAME
                                       password:AUTH_PASS
                                       persistence:NSURLCredentialPersistenceForSession];


        [[challenge sender] useCredential:credentail forAuthenticationChallenge:challenge];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error Message" message:@"Invalid credentails" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

/**
 store auth credentials
 */
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
    NSLog(@"using credential storage");
    return YES;
}

【问题讨论】:

    标签: http uiwebview authorization


    【解决方案1】:

    您可以在 url 而不是请求标头中通过身份验证 请尝试代替 BASE_URL:

    NSString* urlString = [NSString stringWithFormat:@"%@//%@:%@@%@",@"http:",userName,password,myUrl]
    

    【讨论】:

    • OP 专门要求基本身份验证,而不是解决它。
    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 2013-05-16
    • 2015-07-22
    • 2013-09-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多