我正在开发一个 iOS 应用程序,它需要在 UIWebView 中显示来自服务器的网页,同时根据需要注入(inject)相关的本地 png 和 css 文件以加快加载时间。这是我用来尝试执行此操作的代码:
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 加载新网页 URL就像我使用 loadRequest 方法一样。
我的问题是如何让 UIWebView 表现得像加载请求一样,同时仍然从 baseurl 注入(inject)本地文件?
谢谢
最佳答案
按钮中的相关链接不起作用,因为链接页面位于远程服务器上,而不是设备的文件系统上。但是,您可以使用 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 上设置委托(delegate),否则将不会调用此方法。
关于html - 在不破坏链接的情况下将本地文件注入(inject) UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10893893/