更新:这个问题似乎在 iOS 7.0.3 中得到修复
我在 Apple 开发者论坛上回答了这个问题,但是现在 iOS7 已经过测试版了,我会在这里重新发布。目前 Windows 身份验证在 iOS7 中被破坏。我希望很快就会有一个修复,但在那之前你可以通过在包含你的 UIWebView 的 UIViewController 中处理身份验证挑战来解决这个问题。
本质上你
- 自己创建一个 NSURLRequest 和 NSURLConnection
- 处理连接:didReceiveAuthenticationChallenge:
- 在连接中:didReceivedResponse 手动将您的数据加载到 UIWebView
下面我正在加载 PDF,但无论您的内容类型如何,该过程都相同。
//Make sure you implement NSURLConnectionDelegate and NSURLConnectionDataDelegate in your header
@interface MyViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) NSURLConnection *conn;
@property (strong, nonatomic) NSMutableData *pdfData;
@end
@implementation MyViewController
//... all of your init and other standard UIViewController methods here...
//Method that loads UIWebview. You'll probably call this in viewDidLoad or somewhere similar...
- (void) loadWebView {
//Make Request manually with an NSURLConnection...
NSString *url = //Get your url
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
self.conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
//#pragma mark - NSURLConnectionDelegate
//Handle authentication challenge (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if([challenge previousFailureCount] == 0) {
NSString *username = //Get username
NSString *password = //Get password
//Use credentials to authenticate
NSURLCredential *cred = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
} else {
//Cancel authentication & connection
[[challenge sender] cancelAuthenticationChallenge:challenge];
[self.conn cancel];
self.conn = nil;
}
}
//#pragma mark - NSURLConnectionDataDelegate
//Received response (NSURLConnectionDataDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//Init data
self.pdfData = [NSMutableData data];
}
//Collect data as it comes in (NSURLConnectionDataDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.pdfData appendData:data];
}
//Handle connection failure (NSURLConnectionDataDelegate)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//Clean up...
[self.conn cancel];
self.conn = nil;
self.pdfData = nil;
//TODO: Notify user and offer next step...
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Finally, load data into UIWebview here (I'm loading a PDF)...
[self.webView loadData:self.pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];
}
@end