【问题标题】:shouldStartLoadWithRequest: not called for imagesshouldStartLoadWithRequest:不为图像调用
【发布时间】:2017-06-21 10:20:16
【问题描述】:

我有一个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

【问题讨论】:

    标签: ios objective-c uiwebview nsurlrequest nsurlcache


    【解决方案1】:

    shouldStartLoadWithRequest 方法仅在页面加载时调用(即,当整个页面被加载或当框架的内容被加载时),而不是在加载单个资源(如图像、JavaScript 或 CSS)时调用。

    如果您想处理来自 UIWebView 的所有 HTTP/HTTPS 请求,我知道这样做的唯一方法是使用自定义 NSURLProtocol 子类。有关如何执行此操作的示例,请参阅 Apple 的 Custom HTTP Protocol 示例代码项目。

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 1970-01-01
      • 2012-01-21
      • 2013-09-13
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多