监听UIWebView的所有请求

4

我可以通过以下方式拦截UIWebView的初始加载请求:

(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType.

我如何记录我正在加载的页面上的所有请求?


你成功了吗? - Léo Natan
没有,据我所知是不可能拦截WebView发送的单个HTTP请求的。 - DamirDiz
3个回答

9
更新:另一种选择是使用NSURLProtocol来截取应用程序发出的请求,包括所有来自Web视图的请求。
我建议一个创造性的解决方案。虽然这不是您想要的,但由于SDK目前无法实现这一点,这是唯一可能的解决方案。
@interface PrintingCache : NSURLCache
{
}
@end

@implementation PrintingCache

- (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request
{
    NSLog(@"url %@", request.URL.absoluteString);

    return [super cachedResponseForRequest:request];
}
@end

现在,在您的应用程序委托中执行以下操作:
NSString *path = ...// the path to the cache file
NSUInteger discCapacity = 10*1024*1024;
NSUInteger memoryCapacity = 512*1024;

FilteredWebCache *cache = [[Printing alloc] initWithMemoryCapacity: memoryCapacity diskCapacity: discCapacity diskPath:path];
[NSURLCache setSharedURLCache:cache];

这将创建一个共享缓存,所有你的应用程序URL请求都将通过此缓存进行,包括你的Web视图。但是,你可能会从其他来源获取更多的URL,而这些URL可能不是你想要的。

1
尝试下面的代码。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"url %@", [[request URL] absoluteString]);
return YES;
}

希望它能对你有所帮助。

-3

这个可行:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"url %@", [[request URL] absoluteString]);
return YES;
}

请确保在[super viewDidLoad]中放置webView.delegate = self;,否则它将不会显示任何内容。


1
你刚才是不是复制了另一个 Exploring 的答案?因为那个答案是错误的。 - Popeye

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接