【发布时间】: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