我有一个 UIWebView,它使用此代码使用基本授权导航到网页
NSString *authValue = [NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)];
[urlRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
现在,当点击链接时,webView 的 shouldStartLoadWithRequest
会被触发,但页面不会加载,因为下一页也需要授权。
有没有办法自动将身份验证添加到单击的链接?
谢谢
最佳答案
如何在shouldStartLoad中正确创建新请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
BOOL shouldNavigate = NO;
NSString *existingAuthValue = [request valueForHTTPHeaderField:@"Authorization"];
if (existingAuthValue == nil)
{
NSString *authValue = [NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:request.URL];
//Append any other info from the old request
[webView performSelector:@selector(loadRequest:) withObject:newRequest afterDelay:0];
}
else
{
shouldNavigate = YES;
}
return shouldNavigate;
}
编辑:抱歉,我没有考虑 NSURLRequest != NSMutableURLRequest。我会更新代码。
关于ios - UIWebView 具有授权,单击链接时使用相同的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828239/