我有一个UIWebView
,我让它加载一个HTML字符串。该字符串包含图像的http URL。图像被加载,但不会为它们调用shouldStartLoadWithRequest:
方法。对于about : blank
,它只被调用一次。但是,所有图像请求都成功传递到我的NSURLCache
子类中,并传递到cachedResponseForRequest:
方法。但我想用shouldStartLoadWithRequest:
方法处理请求。可以做些什么吗?如何将这些请求放入委托方法?
以下是代码:
@interface URLCache : NSURLCache
@end
@implementation URLCache
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSLog(@"REQUEST = %@", request.URL);
return [super cachedResponseForRequest:request];
}
@end
@interface ViewController ()<UIWebViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLCache setSharedURLCache:[URLCache new]];
NSString* path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
NSString* html = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
self.webView.delegate = self;
[self.webView loadHTMLString:html baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"URL = %@", request.URL);
return YES;
}
@end
答案 0 :(得分:0)
仅为页面加载调用shouldStartLoadWithRequest
方法(即,当整个页面被加载或加载帧的内容时),而不是在加载图像,JavaScript或CSS等单个资源时
如果您想操纵来自UIWebView
的所有HTTP / HTTPS请求,我知道这样做的唯一方法是使用自定义NSURLProtocol
子类。有关如何执行此操作的示例,请参阅Apple的Custom HTTP Protocol示例代码项目。