stringByEvaluatingJavaScriptFromString引用本地文件

时间:2012-03-22 03:32:18

标签: ios uiwebview stringbyevaluatingjavascr

我的捆绑资源中有一个图像,我需要在webView stringByEvaluatingJavaScriptFromString中作为源文件(src =“”)引用。我可以从网站引用外部图像,但我不知道如何编写本地图像的URL。

怎么可以这样做?

1 个答案:

答案 0 :(得分:0)

一个展示如何做到这一点的例子......

在我的viewDidLoad中,我将一些示例HTML添加到UIWebView中,如下所示:(这可能很容易被loadRequest:调用远程URL)

NSString *html = @"<html><body><img id='theImage'></img></body></html>";
[self.webView loadHTMLString:html baseURL:nil];

您需要将视图控制器设置为UIWebView的委托,并等待它完成加载HTML。然后,您可以执行脚本来修改图像URL:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // Get the path to the image in the bundle you wish to display, and create a URL from this path.
    NSString *imagePath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyImage.png"]];
    NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
    // Create a script to execute in the web view.
    NSString *script = [[NSString alloc] initWithFormat:@"document.getElementById('theImage').src = \"%@\";", imageURL];
    // Execute the script.
    [self.webView stringByEvaluatingJavaScriptFromString:script];
    // Tidy up.
    [imagePath release];
}