UIWebView has a delay when the load image from url - iphone

I have problem with UIWebView delay when the load image from url.
In my code are lines to load local html file:
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *path = [thisBundle pathForResource:#"detail" ofType:#"html"];
NSString *html = [NSString stringWithContentsOfFile:path];
NSString *htmlString = [NSString stringWithFormat:html, imageURL];
[webView loadHTMLString:htmlString baseURL:nil];
and one of lines in my detail.html file:
<img src="%#" height="100%" alt="…"></img>
And now when I push the button and go to UIWebView, at first it is white and after few seconds show image and text.
I know that time is necessary to load image from URL, but is it possible at first show text and next waiting to load image??
Generally I thinking of: push button -> go to UIWebView -> show text -> show image when it's loaded

There are a few things you could do, one would be to just display a view underneath the uiwebview that displays the text.
Set the uiwebview's alpha to be 0 (so its transparent), then when you receive notification that the uiwebview has finished loading use an animation to fade it in, and then remove the view with text.
You will know when the UIWebView has finished loading when the webViewDidFinishLoad: is called.
For the animation something like this:
[UIView animateWithDuration:0.4
animations:^ {
self.webView.alpha = 1.0;
}];

With the help of Martin H, I managed to solve the problem.
First in my local.html file, I was add in <head> section:
<script type="text/javascript">
function loadImage(imageSource) {
document.getElementById("picture").src=imageSource;
}
</script>
next in <body> section:
<img src="" style="border: none;" id="picture">
and next in my UIViewController I was add delegate method:
- (void) webViewDidFinishLoad:(UIWebView *)web {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"loadImage('http://example.com/image.jpg')"]];
}

Related

Slow loading UIWebView from string

I am trying to load a UIWebView from a string as follows:
NSString* plainContent = #"...";
NSString* htmlContentString = [[NSString stringWithFormat:
#"<html>"
"<style type=\"text/css\">"
"body { background-color:transparent; font-family:Arial-BoldMT; font-size:18;}"
"</style>"
"<body>"
"<p>%#</p>"
"</body></html>", plainContent] retain];
[webView loadHTMLString:htmlContentString baseURL:nil];
Where plain content has some simple HTML with about 5 links and 400 characters. I'm trying to run this on my iPhone5, and the first time it loads it always take a few seconds. Does anyone know why this is happening and how to fix this?
I recently struggled with UIWebView performance. It seemed to take a very long time to process the local HTML I was providing (1 or 2 seconds on iPad Air 2 simulator) even if it was ridiculously small.
After a lot of googling around, I found that the culprit was the phone numbers detection on webview. Once I unchecked it on the storyboard, the latency was gone.
Hope it helps someone facing the same issue :)
This usually happens because of CSS used in rendering web page. It is default behavior when loading page locally. We can also consider that in first load, UIWebview doesn't have cache to this and create cache for that page.
To make it little fast try loading page from a file e.g.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"filePath" ofType:#"html" inDirectory:#"."]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
CSS like body { background-color:transparent; font-family:Arial-BoldMT; font-size:18;} also increase the time of loading a page.
For other who experienced this problems, sometimes we created HTML file by copy-paste-ing from existing websites and we're forget to check the links on header.
In my case, I forgot to remove unused link rel in my html string header:
NSString* html = [NSString stringWithFormat:#"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>%#</title><link type=\"text/css\" rel=\"stylesheet\" href=\"http://192.168.3.183/assets/css/question.css?1383042738\" /></head><body><h1 style=\"font-size: 2em; margin-bottom: 0; color: #3357b8; font-weight: bold\">%#</h1><div style=\"color: #555\">%#</div><br><p style=\"line-height: 1.7em\">%#</p><b>Open in browser</b><br></body></html>", title, title, dateString, content, detail];
The local URL pointed by above link rel make loading time even worst.
<link type=\"text/css\" rel=\"stylesheet\" href=\"http://192.168.3.183/assets/css/question.css?1383042738\" />
Just don't forget to re-check your header or other link in your HTML string and remove it if it is not used.
In case of WKWebView, disabling WKWebView's data detectors worked for me. Swift version:
let webViewCofig = WKWebViewConfiguration()
webViewCofig.dataDetectorTypes = []
webView = WKWebView(frame: view.frame, configuration: webViewCofig)
To enable specific data detector, pass the specific type as .address,.link etc while setting dataDetectorTypes:
config.dataDetectorTypes = [.address]

xcode UIWebView loader code HTML

I've a question about load inside the web view:
I create a Json file to get Wordpress table and work well but inside the content table i can get only pure HTML code in one Line, so if i do a request from the web view to load the content like standard code i can't see the content, but only pure code with tags:
[MyWeview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:MyJsonClass.MyContentTeble ]]];
This normal code working, but not to encode HTML, i will get code like:
NSString *HTMLData = #"<iframe></iframe>";
[palinsesto loadHTMLString:HTMLData baseURL:nil];
But my code #"" is get from MyJsonClass.MyContentTable
Thanks for help.
//---------------------------------------------------------------------//
Thx for you answer White, but still not working, if i try to use that code:
[MyWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:MyJsonClass.MyContentTeble ]]];
Working, but i cant see the content.
I try your code and built app good, but crash after touch UITable Cell.
Think i need a Encoder inside the App to read and compile like a NormalWebBrowser a simple HTML code, but never <html><body></body></html> tags T_T because i get pure code and tex from WordPress Table on Mysql DB.
Any other idea?
you might try the following:
[web loadHTMLString: # "<html> <body> <iframe src = 'http://www.example.com', style = 'border-width: 0' width = '100% 'height = '480' frameborder = '0 'scrolling =' no '> </ iframe> </ body> </ html> "baseURL: nil];
- (BOOL) WebView: (UIWebView *) WebView shouldStartLoadWithRequest: (NSURLRequest *) request navigationType: (UIWebViewNavigationType) {navigationType
if ([request.URL.absoluteString rangeOfString: # "www.example.com"]. location! = NSNotFound) {
NSLog (#"%#", [WebView stringByEvaluatingJavaScriptFromString: # "document.body.innerText"]);
return NO;
}
return YES;
}
This is an idea.
I hope you can help

How To Parse html String from UIWebview for richtexteditor in iphone

I am using RichTextEditor exactly as detailed in this link and I need to show the written content in table view in other class on a button click, but in the table view cell, corresponding html string is appearing. Following is my code
-(void)submitClicked{
contentObject.webCOntent=webView;
contentObject.savedMessage=SAVED;
contentObject.str = [webView stringByEvaluatingJavaScriptFromString:
#"document.body.innerHTML"];
NSLog(#"created %#",contentObject.str);
}
in tableView cellforRowAyIndexPath,
cell.textLabel.text = [[notesArray objectAtIndex:indexPath.row]str ];
When I run the app,its Showing in tableview
Oiuo8
where, contentObject is modelclass object and str is string and webcontent is UIWebView in model class
I got the solution finally by changing contentObject.str = [webView stringByEvaluatingJavaScriptFromString:
#"document.body.innerHTML"]; to
contentObject.str = [webView stringByEvaluatingJavaScriptFromString:
#"document.documentElement.textContent"];,its giving the normal text instead of html text.

UIWebview manipulating SVG 'on the fly'

I would like to know how to manipulate SVG files that I have loaded into a UIWebview. Currently I am loading an SVG file into an HTML file and then loading that into a UIWebview. I presume that you would use Javascript to do this but am not sure how the go about it exactly. Ideally I would like to be able to manipulate the SVG on the fly in an iPad app. I am aware that you can 'inject' code into the UIWebview but have had no success with my attempts. Clear as mud? Well perhaps a bit of code will help.
Here is how I load the html file into the UIWebview inside the view controller .m file:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString* path = [[NSBundle mainBundle] pathForResource:#"SVG" ofType:#"html"];
NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
webView = [UIWebView new];
webView.frame = CGRectMake(0, 0, 1024, 768);
webView.dataDetectorTypes = UIDataDetectorTypeAll;
webView.userInteractionEnabled = YES;
[webView loadHTMLString:content baseURL:[[NSBundle mainBundle] bundleURL]];
[self.view addSubview:webView];
[webView release];
}
Here is the code inside the html file that is loaded into the UIWebview:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SVG</title>
</head>
<body>
<object id="circle" data="Circle.svg" width="250" height="250" type="image/svg+xml"/>
</body>
</html>
...and finally here is the code inside the SVG file:
<svg xmlns="http://www.w3.org/2000/svg">
<circle id="redcircle" cx="200" cy="50" r="50" fill="red" />
</svg>
Which creates a nice little red circle in the UIWebview. Now I would like to be able to manipulate the circle on the fly back in the view controller .m file. For example when the user touches the iPad screen, change the fill color attribute to green. Is this even possible?
I hope this all makes sense. It's a bit convoluted. But ultimately what I am trying to do is create graphics on the fly with SVG in an HTML framework and display it in a UIWebview.
Any help would be appreciated. Thanks.
You can execute arbitrary Javascript by passing it to stringByEvaluatingJavaScriptFromString on the webView at any point after the page has first loaded - like in response to a touch event.
So if the Javascript to find the SVG object and change the color looks something like (YMMV, haven't actually tested this):
var path=document.getElementById("circle").getSVGDocument().getElementById("redcircle");path.style.setProperty("fill", "#00FF00", "");
You can execute it with:
NSString *string = #"var path=document.getElementById('circle').getSVGDocument().getElementById('redcircle');path.style.setProperty('fill', '#00FF00', '');";
[webView stringByEvaluatingJavaScriptFromString:string];

If statement in Xcode to determine which HTML page is being loaded by a UIWebView

I have a UIWebView on my interface and I have added a UIToolbar with a next button and previous button. When I press the next button, I want the WebView to load a different HTML page. BUT I also want to run an if statement to determine which HTML page the WebView currently has in it.
So For example.
If the UIWebView has index.html loaded in it,
when the user presses the next button I want it to load about.html.
If the UIWebView has about.html loaded in it,
when the user presses the next button I want it to load contact.html. etc.
Here is the way I am setting the WebView:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"PrepareEquipment" ofType:#"html"]isDirectory:NO]]];
Thanks guys!
Stefan.
How about a simple array or other collection where you store all your pages in the order they should be shown?
NSArray *pagesArray = [NSArray arrayWithObjects:#"index.html", #"about.html", #"contact.html", nil];
NSString *currentPage = [pagesArray objectAtIndex:0];
...
- (NSString *)getNextPage {
int pageIndex = [pagesArray indexOfObject:currentPage];
++pageIndex;
pageIndex%= [pagesArray count];
NSString *nextPage = (NSString *)[pagesArray objectAtIndex:pageIndex];
currentPage = nextPage;
return nextPage;
}
... and a similar method for going back?
Completely untested...