UIWebView loads HTML from local file but fails occasionally - objective-c

I've come across many ways to load and reload the content of a UIWebView from a local html file but it seems like the issue I have keeps coming back.
On my project I have a webView that dynamically loads HTML content pulled from one of the 50 different HTML files I have in my XCode project.
Depending on which button the user presses on the viewController before, a different HTML file is used to reload the content of my webView. Everything works fine most of the time but every now and then, the webView will simply display "(null)", after the webViewDidFinishLoad delegate method is called.
I don't understand what is going on, and when I go back and forth on this viewController and the webView is reloaded the HTML content ends up showing up properly eventually for the same HTML file.
Here is the code to load the HTML in the webView (called from the viewWillAppear method) :
- (void) reloadWebViewFromLocalFile{
// Reset the UIWebView
[self.contentWebView removeFromSuperview];
self.contentWebView = nil;
self.contentWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
[self.contentWebView setContentMode:UIViewContentModeScaleAspectFit];
[self.contentWebView setDelegate:self];
[self.contentScrollView addSubview:self.contentWebView];
[self.contentWebView release];
NSString *fileName = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%d.%d",self.currentIndexPath.section+1,self.currentIndexPath.row+1] ofType:#"html"];
NSString *CSSContent = [NSString stringWithFormat:#"<style type=\"text/css\">body{padding-left:8px;padding-right:8px;font-family:\"%#\";}p{text-align:justify;}img{max-width:300px;display:block; margin:auto;}strong{font-family:\"%#\";}h1{font-size:20;font-family:\"%#\"}h2{font-size:18;font-family:\"%#\"}h3{font-size:17;font-family:\"%#\"}</style><script type=\"text/javascript\">touchMove = function(event) {event.preventDefault();}</script>", FONT_STAG_BOOK, FONT_STAG_SEMIBOLD, FONT_STAG_SEMIBOLD, FONT_STAG_SEMIBOLD, FONT_STAG_SEMIBOLD];
self.HTMLString = [NSString stringWithFormat:#"<html><head>%#</head>%#</html>",CSSContent,[NSString stringWithUTF8String:[[NSData dataWithContentsOfFile:fileName] bytes]]];
[self.contentWebView loadHTMLString:self.HTMLString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
}
and this is the webViewDidFinishLoad delegate method :
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *stringContent = [self.contentWebView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
float height = [[self.contentWebView stringByEvaluatingJavaScriptFromString:#"document.body.offsetHeight;"] floatValue] + 20;
[self.contentWebView setFrame:CGRectMake(0, 0, 320, height)];
[self.contentScrollView setContentSize:CGSizeMake(0, height+self.nextButton.frame.size.height)];
[self.nextButton setFrame:CGRectMake(0, height, 320, self.nextButton.frame.size.height)];
if ([self.contentWebView respondsToSelector:#selector(scrollView)]) {
self.contentWebView.scrollView.scrollEnabled = NO; // available starting in iOS 5
} else {
for (id subview in self.contentWebView .subviews)
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
((UIScrollView *)subview).scrollEnabled = NO;
}
}
Edit : Forgot to copy-paste the line that actually loads the HTML string in the webView

The problem seems to be using the bytes function, which doesn't work too well if the content encoding isn't exact...
[NSString stringWithUTF8String:[[NSData dataWithContentsOfFile:fileName] bytes]];
should be
[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileName] encoding:NSUTF8StringEncoding];

Related

Javascript return a string to objective c

i got a webview and i would like to capture an input from a webview HTML form. i have tried but i cant can some one help me please
this is my webview code
// Init Web View
UIWebView *webView;
webView = [[UIWebView alloc] initWithFrame:boundsRect];
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
webView.scalesPageToFit = YES;
webView.contentMode = UIViewContentModeCenter;
webView.multipleTouchEnabled = NO;
webView.userInteractionEnabled = YES;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
[self addSubview:webView];
[webView release];
return self;
To get value from webView, i used below code.
NSString* value = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementById('text').value"]‌​;
NSLog(#"got: %#",value);
You could look into how phonegap http://phonegap.com/ solves this.

Adding code to a storyboard's UIImageview

I'm trying to get an image from an URL and display it within a UIImageview.
However, I can't connect my code to my image because I don't know how to.
Previously I just made a nib file and do the coding there, but since I transfered my App to iOS 6 and would like to use a storyboard I don't know how to achieve the same thing:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * imageURL = [NSString stringWithFormat:#"http://app-content.app.com/api_ios/images/%#.png",
[[NSUserDefaults standardUserDefaults] objectForKey:#"setup"]];
NSURL* url = [NSURL URLWithString: imageURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * image = [UIImage imageWithData:imageData];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
}
As you can see, I'm loading an image from a website and change a string from the URL with the string from the NSUserdefaults.
I would like to link imageview to the image in my storyboard but it won't let me, nor can I use an identifier on the UIimageview.
What is the right way to do this with a storyboard?
Pedros was right, the IBoutlet was not connected the right way.
It is working now.

How to tell when UIWebView has finished displaying content

I'm making a UIWebView load a pdf like this:
UIWebView *pdfView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
pdfView.delegate = self;
[pdfView loadRequest:request];
And then doing some stuff with the view once it loads:
- (void)webViewDidFinishLoad:(UIWebView*)sender {
[sender takeScreenshot]; // my UIView category screenshot method
[sender release];
}
It all works, apart from the fact that at the point webViewDidFinishLoad is called, the view hasn't displayed anything yet, it displays a few milliseconds later. So is there any way to tell when the UIWebView has finished displaying its content (a pdf in this case)?
You could do:
[self performselector:#selector(getScreenshot) withObject:sender afterDelay:0.1];
-(void) getScreenshot:(UIWebView *)webView {
[webView takeScreenshot];
[webView release];
}
Or something similar.

Objective-C – UIWebView bug found?

I'm setting my UIWebView's size to be 276 pixels wide.
Then I load some html in it and the width of UIWebView is no longer 276 pixels.
I setup the UIWebView as following:
// Setup Career about WebView
r.origin.x = 22;
r.origin.y = kWebViewYPos;
r.size.width = 276;
r.size.height = 1;
UIWebView *tmpAboutWebView = [[UIWebView alloc] initWithFrame:r];
[self setSeminarAboutWebView:tmpAboutWebView];
[tmpAboutWebView release];
[[self seminarAboutWebView] setAutoresizesSubviews:YES];
[[self seminarAboutWebView] setUserInteractionEnabled:YES];
[[self seminarAboutWebView] setTag:999];
[[self seminarAboutWebView] setDelegate:self];
self.seminarAboutWebView.layer.borderColor = [UIColor redColor].CGColor; //Debugging
self.seminarAboutWebView.layer.borderWidth = 1.0; //Debugging
// Load the description for the selected seminar
NSString *htmlString = [[NSString alloc] initWithString:[[self seminar] about]];
DLog(#"%#", htmlString);
NSString *myDescriptionHTML = [NSString stringWithFormat:#"<html> \n"
"<head> \n"
"<link rel=\"stylesheet\" type=\"text/css\" href=\"career.css\" /> \n"
"</head> \n"
"<body>%#</body> \n"
"</html>", htmlString];
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[self.seminarAboutWebView loadHTMLString:myDescriptionHTML baseURL:baseURL];
[htmlString release];
What could be causing this behaviour? Could the HTML contain some tags that make the UIWebView go bananas?
I'm building with iOS 4.3 SDK.
Link to html code
EDIT: I actually found the bug, I believe it was a bug in my own code not in UIWebView. I am dynamically setting the height of the UIWebView depending on how much HTML is loaded in the UIWebView. For this purpose I was using this code:
// Change the height dynamically of the UIWebView to match the html content
CGRect webViewFrame = webView.frame;
webViewFrame.size.height = 1;
webView.frame = webViewFrame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
webViewFrame.size = fittingSize;
// Making sure that the webView doesn't get wider than 276 px I needed to add the below line and now it works
webViewFrame.size.width = 276;
webView.frame = webViewFrame;

How to zoom webView with pdf file

How to get zoom in UIWebView.
I loaded pdf file from resource bundle in a UIWebView.
Now trying to zoom the webview. so its will get zooming effect to the pdf file.
So.
How can i zoom the UIWebView.
Any sample example. Please help me out.
Just use the following code:
self.pdfviewwebview.scalesPageToFit = YES;
self.pdfviewwebview.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.pdfviewwebview.delegate = self;
The most tricky thing here which most people forget is to set the webview's delegate,so take care about that.
UIWebView *tempWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height)];
tempWebView.backgroundColor = [UIColor whiteColor];
**tempWebView.scalesPageToFit = YES; //this enables the zooming**
tempWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
tempWebView.delegate = self;
[self.view addSubview:tempWebView];
[self setWebView:tempWebView];
NSString *path = [[NSBundle mainBundle] pathForResource:#"your_file" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[self.webView loadRequest:request];
A pinch-to-zoom gesture can be simulated by holding down the Option key. On your simulator, two grey circles will appear indicating that its simulating a multi-touch, pinch-to-zoom gesture.