2012-06-05 21 views
2

我正在研究一個iOS應用程序,它需要根據需要在注入相關本地png和css文件的同時顯示UIWebView中的服務器的網頁,以加快加載時間。下面是我使用的嘗試做這樣的代碼:在不中斷鏈接的情況下將本地文件注入到UIWebView中

NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/index.html"]]]; 
NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding]; 
[myWebView loadHTMLString:myFileHtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; 

我的問題是,一些網頁有按鈕在他們的服務器上鍊接到其他網頁,並且因爲一個UIWebView只裝載一個字符串,點擊按鈕不會導致UIWebView加載新的網頁網址,就像我使用loadRequest方法時一樣。

我的問題是如何讓UIWebView的行爲像它正在加載請求,同時仍然從baseurl注入本地文件?

感謝

+0

按鈕鏈接相對或絕對鏈接? – joern

回答

0

的按鈕無法工作相對鏈接,因爲鏈接頁面位於遠程服務器上,而不在設備的文件系統上。然而,你可以使用一個UIWebViewDelegate方法,使其工作:

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

    if (navigationType == UIWebViewNavigationTypeLinkClicked) { 
     NSString *localRootPath = [NSString stringWithFormat:@"file://%@", [[NSBundle mainBundle] bundlePath]]; 
     NSString *remoteRootPath = @"http://yourdomain.com"; 

     NSString *remotePath = [[request.URL absoluteString] stringByReplacingOccurrencesOfString:localRootPath withString:remoteRootPath]; 

     [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:remotePath]]]; 

     // or you can use your own loading mechanism here 

     return NO; 
    } 

    return YES; 
} 

這種方法截取所有從您的WebView請求。如果請求是由用戶點擊/單擊觸發的,則將URL從相對URL修改爲絕對URL,以便可以從服務器加載。不要忘記在WebView上設置委託,否則將不會調用此方法。

0

NSURLPRotocol是NSURLConnection的處理程序,將讓您有機會攔截到服務器的調用和替換自己的內容。

1)派生類從NSURlProtocol

2)呼叫NSURLProtocol的registerClass:在您的應用程序:didFinishLaunchingWithOption

3)閱讀在必要時實施這些方法的文檔: initWithRequest:cachedResponse:客戶:, startLoading, URLProtocol:didReceiveResponse:cacheStoragePolicy: URLProtocolDidFinishLoading:

相關問題