I have loaded PDF in UIWebView
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"ConferenceMap_2014" ofType:#"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[webViewPDF loadData:pdfData MIMEType:#"application/pdf" textEncodingName:#"utf-8" baseURL:nil];
}
Error : DiskImageCache: Could not resolve the absolute path of the old directory.
Hi download the class file from here.
then import the "UIView+DocumentView.h"
after that get the path of particular file
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"file1427464777.586564" ofType:#"pdf"];
Next call the class with particular path
[self.view makeDocumentView:thePath];
I am loading a local HTML into a UIWebView as follows :
- (void)viewDidLoad
{
[super viewDidLoad];
//Setup our UIWebView
webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.delegate = self;
webView.scalesPageToFit = YES;
webView.userInteractionEnabled = YES;
[self.view addSubview:webView];
...
[self loadWebPage];
}
- (void)loadWebPage {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
}
And in the header :
#interface ViewController : UIViewController <UIWebViewDelegate>
However for some reason my webview delegates are not being called :
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"Starting HTML Load Process");
}
- (void)webViewDidFinishLoad:(UIWebView *)webViewRef {
NSLog(#"Web View Finished Loading Method");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Error loading HTML ! %#", error);
}
Can anyone suggest why ?
Thanks !
Called the method [self loadWeb];
But on definition the method is - (void)loadWebPage;
Is it typo?
The only way I can reproduce is this by declaring the webView #property as weak. Can you confirm you are declaring it as a strong reference?
how did you declare your UIWebView instance variable, as a strong or weak? If weak make it strong.
The problem is that this call.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]];
Looks like you're loading the HTML from inside your bundle. This means you need to confirm that all the additional files (.js, .css, and any media files) also need to be present in your bundle.
So the first thing need to check fileURLWithPath: point either it's returning nil or not. If it's not then it means that .html page resolved, however the additional files not resolved as part of the request because it's not placed on the same "index.html" path.
First you need to confirm the directory structure of your "index.html" and all the additional files used inside the page. In order to do that, you have to right click on binary .app in your "build" directory in the finder and then select "Show Package contents".
binary (.app) > right click > Show Package contents
This shows what the app's main bundle contains. Look inside for your HTML file. If it's in a folder, that folder name needs to be in the inDirectory parameter of the pathForResource call. If it's on the top-level then you don't have a folder reference. Either delete & re-drag it into project or use the pathForResource version without inDirectory.
The best way to don't setup the base path or relative path for the resources inside .html page (.js, .css and images) because it don't work. Copy all the additional resources next to "index.html" file so it would be easy to resolve on runtime from bundle.
NSString *path = #"<Index.html Path>";
NSURL *url = [NSURL URLWithString: [path lastPathComponent]
relativeToURL: [NSURL fileURLWithPath: [path stringByDeletingLastPathComponent]
isDirectory: YES]];
Try this
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]isDirectory:NO];
I am using Webview to load a image file stored in my app Library Directory, first i tried use resourcePath, and bundle path
NSString * html = [[NSString alloc] initWithFormat:#"<img src=\"file://%#\"/>", filename];
[self.webView loadHTMLString:newhtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
the problem is no matter what i set in the baseUrl, i can not load the image correctly , i also tried filePath:
[self.webView loadHTMLString:newhtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] filePath]]];
but if i set the absolute path of the image file in the html , all the things is ok, i wonder why?
Have a look at this post: Using HTML and Local Images Within UIWebView
The top answer clearly said that using file: paths to refer to images does not work with UIWebView.
All you need to do is to pass the basepath. Example:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Then just need to reference it like this: <img src="myimage.png">
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
I'm trying to load a html file into my UIWebView but it won't work. Here's the stage: I have a folder called html_files in my project. Then I created a webView in interface builder and assigned an outlet to it in the viewController. This is the code I'm using to append the html file:
-(void)viewDidLoad
{
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"html" inDirectory:#"html_files"];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[webView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#""]];
[super viewDidLoad];
}
That won't work and the UIWebView is blank. I'd appreciate some help.
probably it is better to use NSString and load html document as follows:
Objective-C
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
Swift
let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html!, baseURL: nil)
Swift 3 has few changes:
let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(html!, baseURL: nil)
Did you try?
Also check that the resource was found by pathForResource:ofType:inDirectory call.
EDIT 2016-05-27 - loadRequest exposes "a universal Cross-Site Scripting vulnerability." Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants.
If you need relative links to work locally, use this:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"my" withExtension:#"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
The bundle will search all subdirectories of the project to find my.html. (the directory structure gets flattened at build time)
If my.html has the tag <img src="some.png">, the webView will load some.png from your project.
by this you can load html file which is in your project Assets(bundle) to webView.
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"test" ofType:#"html"]isDirectory:NO]]];
may be this is useful to you.
I guess you need to allocate and init your webview first::
- (void)viewDidLoad
{
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"html" inDirectory:#"html_files"];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
webView = [[UIWebView alloc] init];
[webView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#""]];
[super viewDidLoad];
}
A Simple Copy-Paste code snippet:
-(void)LoadLocalHtmlFile:(NSString *)fileName onWebVu:(UIWebView*)webVu
{
[webVu loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:fileName ofType:#"html"]isDirectory:NO]]];
}
Note:
Make sure the html file's Target membership is checked otherwise following exception will get thrown :-
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'
For Swift 3 and Swift 4:
let htmlFile = Bundle.main.path(forResource: "name_resource", ofType: "html")
let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
self.webView.loadHTMLString(html, baseURL: nil)
UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
//[self.view addSubview:web];
NSString *filePath=[[NSBundle mainBundle]pathForResource:#"browser_demo" ofType:#"html" inDirectory:nil];
[web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];
May be your HTML file doesn't support UTF-8 encoding, because the same code is working for me.
Or u can also these line of code:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"Notes For Apple" ofType:#"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];
Here the way the working of HTML file with Jquery.
_webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
[self.view addSubview:_webview];
NSString *filePath=[[NSBundle mainBundle]pathForResource:#"jquery" ofType:#"html" inDirectory:nil];
NSLog(#"%#",filePath);
NSString *htmlstring=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
or
[_webview loadHTMLString:htmlstring baseURL:nil];
You can use either the requests to call the HTML file in your UIWebview
Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.
A new way to do this using swift. The UIWebView is no more and WKWebView is the new class to load web pages, which ensures the Safari features to the web view.
import WebKit
let preferences = WKPreferences()
preferences.javaScriptCanOpenWindowsAutomatically = false
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let webView = WKWebView(frame: self.view.bounds, configuration: configuration)
let request = NSURLRequest(URL: NSURL(string: "http://nshipster.com"))
webView.loadRequest(request)
Swift iOS:
// get server url from the plist directory
var htmlFile = NSBundle.mainBundle().pathForResource("animation_bg", ofType: "html")!
var htmlString = NSString(contentsOfFile: htmlFile, encoding: NSUTF8StringEncoding, error: nil)
self.webView.loadHTMLString(htmlString, baseURL: nil)
Here's Swift 3:
if let htmlFile = Bundle.main.path(forResource: "aa", ofType: "html"){
do{
let htmlString = try NSString(contentsOfFile: htmlFile, encoding:String.Encoding.utf8.rawValue )
messageWebView.loadHTMLString(htmlString as String, baseURL: nil)
}
catch _ {
}
}
[[NSBundle mainBundle] pathForResource:#"marqueeMusic" ofType:#"html"];
It may be late but if the file from pathForResource is nil you should add it in the Build Phases > Copy Bundle Resources.
if let htmlFile = NSBundle.mainBundle().pathForResource("aa", ofType: "html"){
do{
let htmlString = try NSString(contentsOfFile: htmlFile, encoding:NSUTF8StringEncoding )
webView.loadHTMLString(htmlString as String, baseURL: nil)
}
catch _ {
}
}
In Swift 2.0, #user478681's answer might look like this:
let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
let HTMLString: NSString?
do {
HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!, encoding: NSUTF8StringEncoding)
} catch {
HTMLString = nil
}
myWebView.loadHTMLString(HTMLString as! String, baseURL: nil)
Put all the files (html and resources)in a directory (for my "manual"). Next, drag and drop the directory to XCode, over "Supporting Files". You should check the options "Copy Items if needed" and "Create folder references". Next, write a simple code:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"manual/index" withExtension:#"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
Attention to #"manual/index", manual is the name of my directory!!
It's all!!!! Sorry for my bad english...
=======================================================================
Hola desde Costa Rica. Ponga los archivos (html y demás recursos) en un directorio (en mi caso lo llamé manual), luego, arrastre y suelte en XCode, sobre "Supporting Files". Usted debe seleccionar las opciones "Copy Items if needed" y "Create folder references".
NSURL *url = [[NSBundle mainBundle] URLForResource:#"manual/index" withExtension:#"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
Presta atención a #"manual/index", manual es el nombre de mi directorio!!
When your project gets bigger, you might need some structure, so that your HTML page can reference files located in subfolders.
Assuming you drag your html_files folder to Xcode and select the Create folder references option, the following Swift code ensures that the WKWebView supports also the resulting folder structure:
import WebKit
#IBOutlet weak var webView: WKWebView!
if let path = Bundle.main.path(forResource: "sample", ofType: "html", inDirectory: "html_files") {
webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}
This means that if your sample.html file contains an <img src="subfolder/myimage.jpg"> tag, then the image file myimage.jpg in subfolder will also be loaded and displayed.
Credits: https://stackoverflow.com/a/8436281/4769344