简体   繁体   中英

iOS Load Image in UIWebView

Desperately trying to figue out how to load a local image (saved in local xcode bundle) into the following HTML through a UIWebView. I have spent countless hours following other guides but nothing seems to work, all throw erros. Am trying to add a local image in the following NSString where I have written IMAGEGOESHERE -

{
    [super viewDidLoad];

    self.title = _restaurant.title;

    [[self navigationController] setNavigationBarHidden:NO animated:NO];

    self.activityIndicatorView.hidden = NO;
    [self.activityIndicatorView startAnimating];

    [self loadImageInNewThread];


    NSString *webViewContent = [NSString stringWithFormat:@"<html><head><style>* {font-family:   Helvetica}</style></head><body><center>%@ - %@<br><br><b>Restaurant:</b>%@</b><br>IMAGEGOESHERE<br></center></b></body></html>", _restaurant.openingTime,_restaurant.closingTime, _restaurant.name];

    [self.webView loadHTMLString:webViewContent baseURL:nil];
}

I hope you can help as its driving me mad!

You need to reference first the path of your image:

 NSString *pathImg = [[NSBundle mainBundle] pathForResource:@"yourimage" ofType:@"png"];

and then specify your path in your webViewContent along with the size of your image:

NSString* webViewContent = [NSString stringWithFormat:
                                   @"<html>"
                                   "<body>"
                                   "<img src=\"file://%@\" width=\"200\" height=\"500\"/>"
                                   "</body></html>", pathImg];

This code should work, Just replace yourFile with the name of your PDF, and webView with the name of your webView. Then Replace ofType to the extension of your image.

//PDF View
       //Creating a path pointing to a file.pdf
       NSString *path = [[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"pdf"];
       //Creating a URL which points towards our path
       NSURL *url = [NSURL fileURLWithPath:path];
       //Creating a page request which will load our URL (Which points to our path)
       NSURLRequest *request = [NSURLRequest requestWithURL:url];
       //Telling our webView to load our above request
       [webView loadRequest:request];
NSString *pathImg = [[NSBundle mainBundle] pathForResource:@"yourimage" ofType:@"png"];
NSString* webViewContent = [NSString stringWithFormat:
                               @"<html>"
                               "<body>"
                               "<img src=\"file://%@\" width=\"200\" height=\"500\"/>"
[webView loadHTMLString:webViewContent baseURL:nil];

You must add the last line with a base url of nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM