UIWebView和HTTP Basic Auth的问题

时间:2014-01-09 10:16:10

标签: http uiwebview authorization

我已经在网上搜索了如何在uiwebview中进行基本的http身份验证。我已经尝试了所有这些并且无论我做什么都会得到不一致的结果。有时auth工作,有时它不工作。它正在推动我上升,我会喜欢一些帮助!

这是相关代码。我总是得到一个auth挑战,但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;
}

1 个答案:

答案 0 :(得分:1)

您可以在网址而不是请求标头中传递身份验证 请尝试代替BASE_URL:

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