2

我有一个 UIWebView 使用此代码使用基本授权导航到网页

NSString *authValue = [NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)];
    [urlRequest setValue:authValue forHTTPHeaderField:@"Authorization"];

现在,当单击链接时,shouldStartLoadWithRequest会触发 webView,但不会加载页面,因为下一页也需要授权。

有没有办法自动将 Auth 添加到单击的链接中?

谢谢

4

1 回答 1

5

如何在 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。我会更新代码。

于 2012-10-10T21:31:08.937 回答