Search code examples
iosuiwebviewstringbyevaluatingjavascr

stringByEvaluatingJavaScriptFromString Reference Local File


I have an image that I have in my bundle resources that I need to reference as a source file (src="") in my webView stringByEvaluatingJavaScriptFromString. I can reference external images from websites, but I do not know how to write the URL of the local image.

How could this be done?


Solution

  • An example to show how you could do this...

    in my viewDidLoad, I am adding some example HTML into a UIWebView as shown below: (This could easily be a loadRequest: call to a remote URL)

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

    You need to set the view controller as the delegate for the UIWebView, and wait until it has finished loading the HTML. You can then execute a script to amend the image 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];
    }