UIWebView Delegates Not Triggering ? iOS - 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];

Related

open iBooks from my app with my PDF file from my bundle

It is continuation of open iBooks from my app I did try https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDocumentInteractionController_class/Reference/Reference.html but it is hard to understand with out code sample.
I have iPhone app, that have Web View.
After starting the app Web View opens custom PDF, and this is working fine.
User wil not read that PDF from my app, so I wont to add button that will open that PDF in iBooks (because iBooks have search and lost of other features…).
I have Toolbar on bottom with button for opening my PDF in iBooks.
And this is my problem, I do not have code for opening my PDF in iBooks.
ViewControler.h
#import <UIKit/UIKit.h>
#interface BG_ViewController : UIViewController
{
IBOutlet UIWebView *myWebView;
}
- (IBAction)openInIBooks:(id)sender;
#end
ViewControler.m
#import "BG_ViewController.h"
#interface BG_ViewController ()
#end
#implementation BG_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyBOOK" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[myWebView loadRequest:request];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)openInIBooks:(id)sender
{
NSLog(#"Clicked\n");
// CODE ???
}
#end
What code need to be added to - (IBAction)openInIBooks:(id)sender so that it will open MyBOOK.pdf ???
Best that I have is:
NSString *stringURL = #"itms-books:";
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
But this will just open iBooks app, but with out MyBOOK.pdf.
I tried just to add "itms-books:MyBOOK.pdf", but it is not working :-(
You can open iBooks app from your code by calling [NSURL URLWithString:#"ibooks://"]. But If you want to pass document you should have a look on UIDocumentInteractionController this is a way Apple wants you do do that.

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

UIWebView not loading local .html file

I a trying to view an .html file (index.html) that is stored in my Bundle (in my Supporting Files).
The .html file sits in a folder called HTML. My code is as follows:
- (void)viewDidLoad
{
[super viewDidLoad];
_viewWeb.delegate = self;
NSString *path = [[NSBundle mainBundle]
pathForResource:#"index" ofType:#"html" inDirectory:#"HTML"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_viewWeb setScalesPageToFit:YES];
[self.viewWeb loadRequest:request];
}
My header file looks as follows:
#interface D6ViewController : UIViewController <UIWebViewDelegate>
{
IBOutlet UIWebView *viewWeb;
}
#property (weak, nonatomic) IBOutlet UIWebView *viewWeb;
#end
I synthesized property as viewWeb = _viewWeb. The viewcontroller holding the UIWebView loads fine but shows a white screen with no webpage. I have set the outlets in the IB.
Any ideas? Thanks,
You are using a relative path (hence the blue color of a folder). You can actually find the answer to this problem here Load resources from relative path using local html in uiwebview or below:
Drag the resource into your xcode project, you will get two options "create groups for any added folders" and "create folders references for any added folders". Select the "create folder references.." option.
The code below should work.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html" inDirectory:#"/HTML"]];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
try this
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"]isDirectory:NO]]];
In Swift:
func pathForResource(name: String?, ofType ext: String?, inDirectory subpath: String?) -> String?
- name: Name of Hmtl;
- ofType ext: extension for type of file. In this case "html";
- inDirectory subpath: the folder where are the file. In this case the file is in root folder;
let path = NSBundle.mainBundle().pathForResource("dados", ofType: "html", inDirectory: "root")
var requestURL = NSURL(string:path!);
var request = NSURLRequest(URL:requestURL);
webView.loadRequest(request)
You are wrong, here is the correct code:
var requestURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "www")!)
var request = NSURLRequest(URL:requestURL!)
myWebView.loadRequest(request)
You can use this If you are not saving your HTML file in any directory.If you are saving your HTML file in any directory then specify the directory name in "inDirectory" parameter.
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:#""]];

How to use local resources to speed up webview in iOS?

I'm loading a remote webpage into an iOS webview which relies on js and css assets. To improve the performance particularly on 3G networks, I'm hoping to call these assets from files local to the iOS device.
The website backing the iOS app is also used by mobile phone browsers, not just the iOS app, so subclassing NSURLRequest to register my own URL prefix (myurl://) is not ideal.
I already have code that launches mobileSafari for URLs outside of my domain:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSString *hostname = [url host];
if (![hostname hasSuffix:#".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
return YES;
}
This method is called from the same controller implementation with code like this:
- (void)viewDidLoad {
[super viewDidLoad];
// ...
webView.delegate = self;
// ...
NSURL *url = [[NSURL alloc] initWithString:([path length] > 0 ? path : #"http://mysite.com/mobile/index")];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
// ...
}
I've reviewed several other questions ( How to use an iPhone webView with an external HTML that references local images? , Dynamically loading javascript files in UIWebView with local cache not working, iOS WebView remote html with local image files, Using local resources in an iPhone webview ) but they all seem to miss a key element to my problem.
The first link has the start of something promising:
if ([url isEqualToString:#"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
fileToLoad = [[NSBundle mainBundle] pathForResource:#"jquery-1.8.2.min" ofType:#"js"];
}
If that's a sensible approach, I'm stuck on how to get from passing that fileToLoad NSBundle into the webView's loadRequest, since that's expecting a URL.
I think I'm on the right path after realizing that I could use the output of stringByAppendingPathComponent as a URL, like so...
if (![hostname hasSuffix:#".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
NSString *urlString = [url absoluteString];
if ([urlString isEqualToString:#"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
NSString *tempurl = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"js/jquery-1.8.2.min.js"];
[webView loadRequest:[NSMutableURLRequest requestWithURL:tempurl]];
} else {
[[UIApplication sharedApplication] openURL:url];
}
return NO;
}
return YES;
I don't have it working yet (it's still loading the remote URL) but I think I'm on the right path.

stringByEvaluatingJavaScriptFromString Reference Local File

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

Resources