stringByEvaluatingJavaScriptFromString Reference Local File - ios

I have an image that I have in my bundle resources that I need to reference as a source file (src="") in my webView stringByEvaluatingJavaScriptFromString. I can reference external images from websites, but I do not know how to write the URL of the local image.
How could this be done?

An example to show how you could do this...
in my viewDidLoad, I am adding some example HTML into a UIWebView as shown below: (This could easily be a loadRequest: call to a remote URL)
NSString *html = #"<html><body><img id='theImage'></img></body></html>";
[self.webView loadHTMLString:html baseURL:nil];
You need to set the view controller as the delegate for the UIWebView, and wait until it has finished loading the HTML. You can then execute a script to amend the image URL:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// Get the path to the image in the bundle you wish to display, and create a URL from this path.
NSString *imagePath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"MyImage.png"]];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
// Create a script to execute in the web view.
NSString *script = [[NSString alloc] initWithFormat:#"document.getElementById('theImage').src = \"%#\";", imageURL];
// Execute the script.
[self.webView stringByEvaluatingJavaScriptFromString:script];
// Tidy up.
[imagePath release];
}

Related

UIWebView Delegates Not Triggering ? iOS

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];

Load Image from UIwebview fail

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">

iOS 6 - Able to save .pdf from URL, able to display it in a WebView, NOT able to move it to iBooks

This is what I'm trying to do:
Get a .pdf from external URL
Save it into my local disk
Display it in a WebView
Allow the user to move the .pdf to another app who can read .pdf
Everything from 1 to 3 works fine. But nothing is moved/shared to/with other apps. I can't understand what I'm doing wrong. This is what I'm doing.
How I save the pdf in the Documents folder (viewDidLoad):
// to save the pdf into local file system (tempString is the pdf url)
NSData *pdfData = [[NSData alloc]
initWithContentsOfURL:[NSURL URLWithString:tempString]];
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePAth atomically:YES];
// to populate the WebView
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[my_web_view setUserInteractionEnabled:YES];
//[editoriale_view setDelegate:self];
[my_web_view loadRequest:requestObj];
In my viewDidLoad() function I create a button to allow the user to open a list of apps who can read .pdf files:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self
action:#selector(show_Button)];
And here's my show_Button function:
-(void)show_Button {
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath
stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
When I try this on my device everything works fine until I tap on one of the icons in the list (i.e. the iBooks one). Then the app closes (it doesn't crash, it simply closes).
Here's what the console prints for the two logs I put in the show_Button function:
1. filePath = /Users/[MY_USER]/Library/Application Support/iPhone
Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
2. url2 = file://localhost/Users/[MY_USER]/Library/Application%20Support/
iPhone%20Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
Anyone wants to try to make me understand what I'm doing wrong? I'm using Xcode 4.6. I browsed my iPhone app file system with a third-party software and the file "MyPDF.pdf" actually IS in the Documents" folder, and that's clear because the WebView is correctly populated.
Change CGRectZero to self.view.bounds when you display the document controller.
Solved. I had not implemented the UIDocumentenInteractionController delegate in the .h file. Now I have and everything works fine. Thank you to #trojanfoe for the useful hint.

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

Run HTML5/CSS3 in UIWebView

I've a problem that i couldn't solve, i wanna run the Apple - HTML5 Showcase - Gallary
in UIWebView inside my ipad app.
I've tried a local html file:
NSString *strr = [[NSBundle mainBundle] pathForResource:#"photo-gallery" ofType:#"html"];
NSString *str = [[NSString alloc] initWithContentsOfFile:strr encoding:NSASCIIStringEncoding error:nil];
NSLog(#"%#",str);
[webView loadHTMLString:str baseURL:nil];
and also a server html file, but it didn't work, can anyone help me, i wanna show an html5/css3 in UIWebView.
thx in advance.
hi this is what you can do
UIWebView *aWebView = [[UIWebView alloc] initWithFrame:webFrame];
//getthe path of the local html file
NSURL *baseURL = [NSURL fileURLWithPath:fileNamePath];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:baseURL];
//load the html file into the web view.
[aWebView loadRequest:aRequest];
//add the web view to the content view
[view addSubview:aWebView];
For server html you simply skip the second line, and put the address.
Hope it helps
You can take a look at phonegap. Its a complete framework for building html5 apps inside a UIWebview with native capabilities.
See: http://www.phonegap.com

Resources