How can I load a local HTML file into the UIWebView? - iphone

How can we load our own html file into the UIWebView?

The following code will load an HTML file named index.html in your project folder:
[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]isDirectory:NO]]];

Cody Gray is right but there's also this way :
// Load the html as a string from the file system
NSString *path = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
// Tell the web view to load it
[WebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
This is useful if you need to edit the html before you load it.

Swift
guard let path = NSBundle.mainBundle().pathForResource("index", ofType: "html") else {
return
}
let url = NSURL(fileURLWithPath: path)
self.webview.loadRequest(NSURLRequest(URL:url))

By using following code you can load an html in an WebView.here web is web view obj and inde
Web.delegate = self;
[Web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]isDirectory:NO]]];

Apple's documentation suggests using loadHTMLString:baseURL::
Use the loadHTMLString:baseURL: method to begin loading local HTML files or the loadRequest: method to begin loading web content. Use the stopLoading method to stop loading, and the loading property to find out if a web view is in the process of loading.
The loadHTMLString:baseURL: documentation offers further reasoning:
To help you avoid being vulnerable to security attacks, be sure to use this method to load local HTML files; don’t use loadRequest:.
This one might help: https://stackoverflow.com/a/29741277

Swift Version 2.1
// load html to String with Encoding
let path = NSBundle.mainBundle().pathForResource("policy", ofType: "html")
do {
let fileHtml = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(fileHtml as String, baseURL: nil)
}
catch {
}

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"privacy-Policy" ofType:#"html" inDirectory:nil];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[webView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#""]];

Related

Showing html file using UIWebView

I have created a UIWebView and used a HTML file to display some contents. But when I run it instead of showing the contents only the whole HTML file coding is coming in the WebView. Please help and tell me what is wrong.
UIWebView *ingradients= [[UIWebView alloc]init];
[ingradients setFrame:CGRectMake(10, 170, 300, 300)];
[ingradients loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"htmlfile" ofType:#"html"]isDirectory:NO]]];
ingradients.delegate=self;
[self.view addSubview:ingradients];
My htmlfile.html contains
<html>
<body>
<p><strong>Ingredients</strong></p>
</body>
</html>
Instead of showing "Ingredients" in bold its showing the whole coding of htmlfile.html
In Your code you alway contain HTML code because your request always return file htmlfile with extantion .html
If you want to get specific value from HTML content you need to Parce HTML content by using Hpple. Also This is documentation with exmple that are use for parse HTML content.
In your case you use: (by using Hpple)
TFHpple *dataParser = [TFHpple hppleWithHTMLData:placesData];
// name of place
NSString *XpathQueryString = #"//p/strong";
NSArray *listOfdata= [dataParser searchWithXPathQuery: XpathQueryString];
That's weird, I have similar code for this and html is rendered as rich text but not as plain text (like you have), the only difference I have is using fileURLWithPath: but not fileURLWithPath:isDirectory:. Here's my code:
NSString *localFilePath = [[NSBundle mainBundle] pathForResource:#"about" ofType:#"html"];
NSURLRequest *localRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:localFilePath]];
[_aboutWebView loadRequest:localRequest];
Maybe you have some issues with file encoding, but as far as I guess, that should not be the case.
Try this code:
- (NSString *) rootPath{
return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
}
- (NSString *) pathFoResourse : (NSString *) resourseName ofType: (NSString *)type{
NSString *path = [[MMSupport rootPath] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", resourseName, type]];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
path = [[NSBundle mainBundle] pathForResource:resourseName ofType:type];
}
NSLog(#"**path:%#**", path);
return path;
}
- (void) loadDataToWebView : (CGRect) frame{
NSString *htmlString = [NSstring stringWithContentsOfFile:[MMSupport pathFoResourse:#"filename" ofType:#"html"] encoding:NSUTF8StringEncoding) error:nil];
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
[webView loadHTMLString:htmlString baseURL:nil];
}

Injecting a local css into UIWebView

I'm trying to "inject" a local css file into downloaded xhtml file.
I found many examples of how to do it, but it just doesn't work for me...
Here is my code:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *cssPath = [path stringByAppendingPathComponent:#"test.css"];
NSString *js = [NSString stringWithFormat:#"var cssNode = document.createElement('link');"
"cssNode.type = 'text/css';"
"cssNode.rel = 'stylesheet';"
"cssNode.href = '%#';", cssPath];
js = [NSString stringWithFormat:#"%#document.getElementsByTagName('head')[0].appendChild(cssNode);", js];
//m_webview is a member
[m_webView stringByEvaluatingJavaScriptFromString:js];
}
What am I doing wrong here?
Thanks,
I also had trouble doing this.
I was trying to load an HTML file from a server and change the styling using a local CSS file.
At first I used
[webView loadRequest:reqObj];
And when it hit - (void)webViewDidFinishLoad:(UIWebView *)webView i was trying to push the CSS file as a child to 'head':
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *cssPath = [path stringByAppendingPathComponent:#"style.css"];
NSString *js = [NSString stringWithFormat:#"var cssChild = document.createElement('link');"
"cssChild = 'text/css';"
"cssChild = 'stylesheet';"
"cssChild = '%#';", cssPath];
js = [NSString stringWithFormat:#"%# document.getElementsByTagName('head')[0].appendChild(cssChild);", js];
[webView stringByEvaluatingJavaScriptFromString:js];
}
So... it didn't work...
then i tried
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
(I copied the HTML string into htmlString) and then, inside - (void)webViewDidFinishLoad:(UIWebView *)webView I injected the CSS as in the code above. And it worked!
But... my HTML file is stored in a remote server and I didn't have the HTML string, so I used
NSString* myFile = [NSString stringWithFormat:#"http://blablabla.com/file.html"];
NSString* myFileURLString = [myFile stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myFileURLString]];
NSString* myFileHtml = [[[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding] autorelease];
To get the HTML. Now, I have the raw HTML text inside ' myFileHtml '.
I now use
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:myFileHtml baseURL:baseURL];
And catching the response in ' webViewDidFinishLoad ', injecting my CSS file into it and it worked :)
Maybe there's another, more elegant, solution to this problem, but this is what I came up with...
Hope it helped.
cssNode.href = '%#';", cssPath];
The line above fails because it tries to fetch the file from the webserver. Using something like:
cssNode.href = 'file://%#';", cssPath];
accesses the local file system. You can use Safari's developer mode to inspect the iPhone simulator and see whether file is found and loaded.
I eventually ended up implementing inline stylesheets instead of linking to stylesheet. Here's the code that works for me
NSError *error;
NSString *css = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"stylesheet" ofType:#"css"] encoding:NSASCIIStringEncoding error:&error];
css = [css stringByReplacingOccurrencesOfString:#"\n" withString:#" "]; // js dom inject doesn't accept line breaks, so remove them
NSString *js = [NSString stringWithFormat:#"var styleNode = document.createElement('style');"
"styleNode.type = 'text/css';"
"styleNode.innerHTML = ' %# ';", css];
js = [NSString stringWithFormat:#"%#document.getElementsByTagName('head')[0].appendChild(styleNode);", js];
[_webView stringByEvaluatingJavaScriptFromString:js];
I ran into this while looking for an answer to the same question. I'm loading an HTML page from a web server into a UIWebView. The HTML already has lots of CSS, appropriate for web viewing. In my case I wanted to display:none a few irrelevant div's.
I didn't want to store the HTML locally then load from the file, so I came up with another solution, conceptually similar to others here but more to my tastes. This is Swift 3. Have this run after the page loads, but before it's displayed:
let css = "#someDiv {display:none;} #otherDiv {display:none;} .someClass {display:none;}"
let js = "var sheet = document.createElement('style');sheet.innerHTML = \"\(css)\";document.body.appendChild(sheet);"
webView.stringByEvaluatingJavaScript(from: js)
maybe this should do the trick? (Not tested in Xcode):
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *cssPath = [path stringByAppendingPathComponent:#"test.css"];
NSString *js = [NSString stringWithFormat:#"var cssNode = document.createElement('link');"
"cssNode.type = 'text/css';"
"cssNode.rel = 'stylesheet';"
"cssNode.href = '%#';", cssPath];
js = [NSString stringWithFormat:#"%#document.getElementsByTagName('head')[0].appendChild(cssNode);", js];
NSString *k = [NSString stringWithFormat:#"var script = %#; %#", cssPath, js];
//m_webview is a member
[m_webView stringByEvaluatingJavaScriptFromString:k];
}
Swift 5:
Before Show WebSite inject css to html
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
config()
}
private func config(){
webView.navigationDelegate = self
guard let url = URL(string: "url") else {
return
}
webView.load(URLRequest(url: url))
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
let css = "Css Code"
let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"
webView.evaluateJavaScript(js, completionHandler: nil)
}
}

Is it possible to send a hash tag to a file url in UIWebView?

I want to load a html page from a file, and append a hash tag to it. Is this possible?
I have tried
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"someFile" ofType:#"html"];
NSURL *fileUrl = [NSURL fileURLWithPath:[filePath stringByAppendingFormat:#"#hashtag"]];
[self.webView loadRequest:[NSURLRequest requestWithURL:fileUrl]];
NSLog(#"fileUrl = %#, reachable? %d", fileUrl, [fileUrl checkResourceIsReachableAndReturnError:nil]);
but this tries to look for the file someFile.html%23hashtag, which can't be found. Is there a way to add the hash after the NSURL object is created?
I've also tried loading the file into a string and using loadHTMLString:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"someFile" ofType:#"html"];
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:fileContents baseURL:[NSURL URLWithString:#"http://someFile.html#hashtag"]];
Here the hash tag does work, but my javascript references inside the html don't work. A follow on question from this approach would be, how do I reference javascript files from html loaded in as a string in a UIWebView, ie, what is the base url?
A hack I can think of is to just put all my javascript files inline in the html and load it as a string, but I'm thinking there must be a better way!
I've not tried this but how about loading the file normally without the hashtag and implementing the UIWebViewDelegate with something like this?
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:#"window.location.href = '#hashtag';"];
}
References:
UIView that takes you to anchor link
Programmatically scroll to an Anchor Tag
As to %23 issue, I don't think Scott Kohlert's replace solution is good.
The following solutions seems better, I just copied it from here
NSURL *baseUrl = [NSURL fileURLWithPath:stringUrl];
NSURL *fullURL = [NSURL URLWithString:#"#jumpto" relativeToURL:baseUrl];
A little bit off topic, I found the Safari on iOS 6.0, 6.1 behaves differenly than on iOS 5.1 and other desktop browsers(including Safari for OSX) regarding handle URL with anchor. For one of my particular document, whether in UIWebview or mobile Safari on iOS 6.0 or 6.1, upon the first load, the page isn't scrolled to the right position, a reload will fix it. Maybe it has something to do with the fact that part of the html is produced by javascript dynamically. Any ideas?
This is how I do it in my code. I append the hashmark to the NSString, then I turn it into an NSURL using fileURLWithPath. Then I replace all instances of %23 back into a #. Its all explained in the code below, but let me know if you have any questions.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"someFile" ofType:#"html"];
NSString *filePathWithHash = [NSString stringWithFormat:#"%##yourDesiredHashTagHere",filePath];
NSURL *theURL = [NSURL fileURLWithPath:filePathWithHash];
//NSURL turns the # into %23 when using fileURLWIthPath. So we need to change it back:
NSString *finalURLString = [[NSString stringWithFormat:#"%#",theURL] stringByReplacingOccurrencesOfString:#"%23" withString:#"#"];
//Then we need to change it back to an NSURL
NSURL *finalURL = [NSURL URLWithString:finalURLString];
//And finally we load this in the webView
[theWebView loadRequest:[NSURLRequest requestWithURL:finalURL]];
You should be able to intercept the NSURLRequest, cast it to a NSMutableURLRequest, then change the URL as follows. All this would happen in shouldStartLoadWithRequest. Make sure you set the UIWebView delegate.
- (void) viewDidLoad
{
self.webView.delegate = self;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"someFile" ofType:#"html"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//Make sure the request is mutable
if(![request isKindOfClass:[NSMutableURLRequest class]])
[NSException raise:#"Need to change the request, but can't" format:#""];
NSMutableURLRequest* mutableRequest = (NSMutableURLRequest*)request;
NSString* newUrl = [NSString stringWithFormat:#"%##hashtag", [[request URL] absoluteString]];
[mutableRequest setURL:[NSURL URLWithString:newUrl]];
return YES;
}
I haven't run into any cases where the request wasn't mutable, but who knows.
Or you may want to set the hash in the original URL (like you were doing), then replace the first occurrence of %23 with # in shouldStartLoadWithRequest.
An addition to #xiang's answer. Below the swift version if you're working with local html files in your app:
let urlString = "relative/path/to/your/index.html"
let anchorString = "#your-anchor"
let baseURL:NSURL? = NSBundle.mainBundle().URLForResource(urlString, withExtension: nil, subdirectory: nil)
if let url:NSURL? = NSURL(string: anchorString, relativeToURL: baseURL) {
// Do something with your URL
}
I think you have to add the hash after you create the file URL
Does it work if you change
NSURL *fileUrl = [NSURL fileURLWithPath:[filePath stringByAppendingFormat:#"#hashtag"]];
to something like:
NSString *urlString = [[NSURL fileURLWithPath:filePath] absoluteString];
NSURL *fileUrl = [NSURL URLWithString:[urlString stringByAppendingString:#"#hashtag"]];
In Swift (with WKWebView):
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let baseURL = Bundle.main.url(forResource: "myFile", withExtension: "html") {
//Load the main page and allow access to its directory
webView.loadFileURL(baseURL, allowingReadAccessTo: baseURL.deletingLastPathComponent())
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let anchor = "#myanchor"
//Use javascript to jump to the location
webView.evaluateJavaScript("location.href = '" + anchor + "'", completionHandler: nil)
}

Remap UIWebView root URL to [[NSBundle mainBundle] bundleURL]

I've got some HTML and some images in my iPhone app, arranged something like:
html/
foo.html
images/
bar.png
I can get bar.png to appear in my UIWebView a couple of different ways -- either loading foo.html from an NSUrl, and walking back up the directory tree from the html directory:
<img src="../images/bar.png"/>
or by loading foo.html into a string, using loadHtmlString, and using [[NSBundle mainBundle] bundleURL] as the baseURL:
<img src="images/bar.png"/>
Both of these are kind of clumsy, though -- in the first case, if I move HTML files around I have to rejigger all the relative paths, and in the second case, I have to ignore the actual path structure of the HTML files.
What I'd like to make work is this --
<img src="/images/bar.png"/>
-- treating the bundleURL as the root of the "site". Is there any way to make this work, or am I doomed to have that translated into file:///images/bar.png and have the file not found?
Only way I can see for you to do this would be to embed a web server in your app. Matt Gallagher has a blog post on this you could start from. Alternatively, CocoaHTTPServer and Mongoose could be dropped into your project.
If I'm not mistaken, you have some files in your project bundle that you want to load in your web view. You can do it simply with these few lines of code:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:#"bar" ofType:#"png"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
I'm assuming that you have a text/html file containing the pattern for your web view. You'll need to add the image as an object there (src="%#"...) and then add the imageURL to the pattern:
NSString *path = [[NSString alloc]initWithString:[[NSBundle mainBundle]pathForResource:#"htmlPattern" ofType:#"html"]];
NSError *error;
NSString *pattern = [[NSString alloc]initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
htmlPage = [[NSString alloc]initWithFormat:pattern,
imageURL;
webView = [[UIWebView alloc] initWithFrame:WEBVIEW_FRAME];
[webView loadHTMLString:htmlPage baseURL:[NSURL URLWithString:path]];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pattern]]];

Correct way to load image into UIWebView from NSData object

I have downloaded a gif image into an NSData object (I've checked the contents of the NSData object and it's definitely populated). Now I want to load that image into my UIWebView. I've tried the following:
[webView loadData:imageData MIMEType:#"image/gif" textEncodingName:nil baseURL:nil];
but I get a blank UIWebView. Loading the image from the same URL directly works fine:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
[imageView loadRequest:request];
Do I need to set the textEncodingName to something, or am I doing something else wrong?
I want to load the image manually so I can report progress to the user, but it's an animated gif, so when it's done I want to show it in a UIWebView.
Edit: Perhaps I need to wrap my image in HTML somehow? Is there a way to do this without having to save it to disk?
I tested the code with PNG ("image/png"), JPG ("image/jpeg") and GIF ("image/gif"), and it works as expected:
[webView loadData:imageData MIMEType:imageMIMEType textEncodingName:nil baseURL:nil];
Now, what's wrong with your app?
the imageData is not a well-formed image data. Try opening the file with a web browser or an image editor to check it.
the MIME type is incorrect. Look at the first bytes of the data to determine the actual file type.
webView is not connected in IB, is nil, is hidden, is covered with another view, is off screen, has a CGRectZero frame, etc.
I did not really try to load image to UIWebView but a google search gives me. I think your image string must have a good path and looks like a URL
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *HTMLData = #"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:#"file:/%#//",imagePath]]];
You can see more details here : Loading local files to UIWebView
UIImage *screenshot= [UIImage imageAtPath:
[[NSBundle mainBundle] pathForResource:#"MfLogo_aboutus" ofType:#"png"]];
NSData *myData = UIImagePNGRepresentation(screenshot);
[vc addAttachmentData:myData mimeType:#"image/png" fileName:#"logo.png"];
You can load urlImage into webview which is not saved locally as shown below code
NSString *str = #"";
str = [str stringByAppendingString:#"http://t3.gstatic.com/images?q=tbn:7agzdcFyZ715EM:http://files.walerian.info/Funny/Animals/funny-pictures-firefox-file-transfer-is-complete.jpg"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
[webView loadData:data MIMEType:#"application/jpg" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#"http://google.com"]];
I had the same problem and I found somewhere else that you have to provide a value in the baseURL parameter. I also had encoding set:
textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#"http://localhost/"]];
When I had nil in the baseURL parameter it would not load. By putting something that's basically irrelevant in there the MS docs all worked.
You may want to try assigning a delegate to the webview and implementing the method:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
To see more specifically what error you're getting. If it doesn't get called, implement the method:
- (void)webViewDidFinishLoad:(UIWebView *)webView
as well, just to make sure something is happening, otherwise there might be an issue with UIWebView (assuming you haven't returned NO from webView:shouldStartLoadWithRequest:navigationType:)
To expand on Ed Marty's comment:
The HTML command to put in a base 64 image is:
<img src="data:image/png;base64,##PUT THE BASE64 DATA HERE###" />
I have a category (I'm not sure where it came from, not me...) available on my website that converts NSData to it's Base64 string representation.
Header
Implementation
Easy enough to do, assuming 'imageData' is the NSData variable containing your image:
[imageData base64Encoding] into the above string.
try this code
// 1) Get: Get string from “outline.plist” in the “DrillDownSave”-codesample.
savedUrlString = [item objectForKey: #"itemUrl"];
// 2) Set: The url in string-format, excluding the html-appendix.
NSString *tempUrlString = savedUrlString;
// 3) Set: Format a url-string correctly. The html-file is located locally.
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:tempUrlString ofType:#”html”];
// 4) Set: Set an “NSData”-object of the url-sting.
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
// 5. Gets the path to the main bundle root folder
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
// 6. Need to be double-slashes to work correctly with UIWebView, so change all “/” to “//”
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
// 7. Also need to replace all spaces with “%20″
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
// Load: Loads the local html-page.
[webView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:[NSString stringWithFormat:#"file:/%#//",imagePath]]];
Here's an alternative method:
Save the image you downloaded into your documents folder.
Then get that image's url. Then write a simple html file
using that image url in the IMG SRC tag.
NSLog(#"url=%#", fileURL); // fileURL is the image url in doc folder of your app
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/toOpen.html",
documentsDirectory];
//create simple html file and format the url into the IMG SRC tag
NSString *content = [NSString stringWithFormat:#"<html><body><img src=%#></body></html>",fileURL];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil]; // now we have a HTML file in our doc
// open the HTML file we wrote in the webview
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"life.html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[yourWebView loadRequest:request];
NSString *pathForFile = [[NSBundle mainBundle] pathForResource: #"fireballscopy" ofType: #"gif"];
NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];
[Web_View loadData:dataOfGif MIMEType:#"image/gif" textEncodingName:nil baseURL:nil];