2017-06-21 96 views
0

我有一個UIWebView,我使它加載一個HTML字符串。該字符串包含圖像的http url。圖像被加載,但不調用shouldStartLoadWithRequest:方法。它只被調用一次,對於about : blank。但是,所有圖像請求都成功傳遞到我的NSURLCache子類中,轉換爲cachedResponseForRequest:方法。但我想處理shouldStartLoadWithRequest:方法中的請求。可以做任何事情嗎?我怎樣才能讓這些請求進入委託方法?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

shouldStartLoadWithRequest方法僅用於頁面加載叫(即,當頁面作爲一個整體被加載或當幀的內容獲取加載),不加載時個人資源,如圖像,JavaScript或CSS。

如果您想操作來自UIWebView的所有HTTP/HTTPS請求,我唯一知道的方法是使用自定義的NSURLProtocol子類。有關如何執行此操作的示例,請參閱Apple的Custom HTTP Protocol示例代碼項目。