1

I have downloaded a couple images and I need to view them in and print them from a UIWebView but I cannot seem to get the path correct to get the images to display in the UIWebView.

Anyone done this successfully?

My images are download to a path Documents/MyFolder/MyImage.jpg

Slee
  • 27,498
  • 52
  • 145
  • 243

1 Answers1

0

Simple: just copy the html you want to display to the documents directory and use relative file paths.

I just tested this and it works. First copy your assets into the user document directory. Here just one image as an example. You could copy a whole directory, etc.

NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *imageURL = [documentsDirectory URLByAppendingPathComponent:@"image.gif"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[imageURL path]]) {
    NSString *bundleImage = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"gif"];
    if (bundleImage) {
        [[NSFileManager defaultManager] copyItemAtPath:bundleImage toPath:[imageURL path] error:nil];
    }
}       

Also copy your html pages (this just shows how I set up the test):

NSString *htmlString = @"<html>Here is a picture: <br>"
"<img src=\"image.gif\" height=100 width=100> "
"</html>";

NSURL *mainPageURL = [documentsDirectory URLByAppendingPathComponent:@"index.html"];
NSLog(@"%@", mainPageURL);
[htmlString writeToURL:mainPageURL atomically:YES encoding:NSUTF8StringEncoding error:nil];

Finally load the page - works like a charm.

[webView loadRequest:[NSURLRequest requestWithURL:mainPageURL]];

A caveat about running this in the iOS Simulator. The URL is different on a Mac. In short, you have to use the format @"file:/.../"and replace all slashes / with double slashes //, and all spaces with %20. More on this in this question.

Community
  • 1
  • 1
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • I have tried every combination of relative path I could think of in my app with no luck. – Slee Aug 16 '11 at 13:47