开发者

using UIWebView with images not included in NSBundle but that have been downloaded

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.jp开发者_开发问答g


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜