Is it possible to cache a html page at applicationDidFinishLauchingOptions() method so that when I want to implement UIWebView the delay taken for loading that html page can be avoided?
Any help would be appreciated.
You can get the data at the time of loading of app itself, and then convert that to NSString or keep that as NSData. After that later when you want to load the page you use like -
For NSString -
NSString *htmlString = // string content
[webView loadHTMLString:htmlString baseURL:baseURLString];
for NSData -
NSData *htmlData = // data content
[webView loadData: MIMEType:#"" textEncodingName:#"" baseURL:#""];
Related
I have an HTML file and JS file in my app. When the web view is loaded I am loading my html file which contains the reference to JavaScript file. I have added the JavaScript file in to my bundle resource for compile sources and in the web view did finish load I am calling a JavaScript function which increases the font size of HTML content but the JavaScript method is not getting called.
This is my code:
NSString *readerstring = #"document.getElementById('reader')";
[webView stringByEvaluatingJavaScriptFromString:[[NSString alloc]initWithFormat:#"adjustFontSize('%#'.contentDocument, '4.0')",readerstring]];
You can change the font size of UIWebView like this,
int fontSize = 20;
NSString *String = [[NSString stringWithFormat:#"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", fontSize];
[myWebView stringByEvaluatingJavaScriptFromString:jsString];
or
[myWebView stringByEvaluatingJavaScriptFromString: #"document.body.style.fontSize = '8px'"];
Hope it will helps you...
Call the JS function after web view finished its loading.
And if you are using any of jQuery functions don forget to add jquery.js and evaluate it.
-(void)webViewDidFinishLoad:(UIWebView *)webView{
NSMutableString *jsStr =[[NSMutableString alloc] initWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"jquery.min" ofType:#"js"]] encoding:NSUTF8StringEncoding];
[WebView stringByEvaluatingJavaScriptFromString:jsStr];
jsStr =[[NSMutableString alloc] initWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"yourown" ofType:#"js"]] encoding:NSUTF8StringEncoding];
[WebView stringByEvaluatingJavaScriptFromString:jsStr];
//evalute your js file before calling its function
[WebView stringByEvaluatingJavaScriptFromString:#"myFunctionToChangethefontSize();"];
//change font size directly
[WebView stringByEvaluatingJavaScriptFromString:#"$('#divContent').css('font-size', '18px');"];
}
Important:
Check whether the JS file in compile resource bundle then you have to remove it from there and add it in copy Bundle Resource.
I have a header string, footer string and body of the HTML page. I need to programmatically include some text in the body and then I need to input all this data in a UIWebView to load the page. I need to input the final HTML string into a UIWebView controler, so that it will launch the page I designed. Could someone please share your ideas how can I achieve this?
Thanks!
You mean something like:
NSString *html = [NSString stringWithFormat: #"<html><head><style>body{background-color:black}</style></head><body>the body goes here</body>"];
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0,76.0,320.0,404.0)];
[myWebView loadHTMLString:html baseURL:nil];
If you, for example, have head stored in headString and body in bodyString you could combine them with:
[NSString stringWithFormat: #"<html>%#%#</html>", headString, bodyString];
I am trying to load a UIWebView with local HTML/CSS that is build to look like a nutrition label. The problem is, the data for the food lies inside of my iPhone app. Do I have to put all of my HTML into one enormous NSString object and concatenate my data into it, or is there a way to load the HTML from a local .html file, but somehow "inject" the data that is stored within Objective-C into it?
If the data to be injected is "safe", you could construct your "enormous NSString object" as a format string, sprinkled with %# markers, and use stringWithFormat: to perform the injection in a single move. This is how I construct the pages in the TidBITS News app, using pieces that all come from RSS. It's really quite painless.
You can load basic html using NSData's method dataWithContentsOfFile and then use javascript to modify html in the way you need.
Code would look something like this (using this example):
NSString *path = [[NSBundle mainBundle] pathForResource:#"food" ofType:#"html"];
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {
[webView loadData:data MIMEType:#"text/html" textEncodingName:#"UTF-8"];
}
[webView stringByEvaluatingJavaScriptFromString:#"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"var field = document.getElementById('field_3');"
"field.value='Calling function - OK';"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:#"myFunction();"];
I would do a hybrid of both- have an HTML file in the app that you load, then replace certain strings in that before giving it to the UIWebView. So for example, you could have a file like this
<html>
<head>
<title><!--foodName--></title>
</head>
<body>
<h1><!--foodName--></h1>
<p>Calories / 100g: <!--foodCalories--></p>
</body>
</html>
You'd load that into Cocoa, then replace your special placeholder comments with the actual values you want.
NSDictionary *substitutions = [NSDictionary dictionaryWithObjectsAndKeys:
#"Carrots", #"foodName",
[NSNumber numberWithInt:20], #"foodCalories",
// add more as needed
nil];
NSMutableString *html = [NSMutableString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"foodCard" ofType:#"html"]
encoding:NSUTF8StringEncoding
error:nil];
for(NSString *substitutionKey in substitutions)
{
NSString *substitution = [[substitution objectForKey:substitutionKey] description];
NSString *searchTerm = [NSString stringWithFormat:#"<!--%#-->", substitutionKey];
[html replaceOccurrencesOfString:searchTerm withString:substitution options:0 range:NSMakeRange(0, [html length])];
}
[webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
Since iOS 2 you can use - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script within a UIWebView subclass to execute JS scripts in your webview. This is the best way to inject data from the "Objective-C part" of your application.
Cf: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:
I new to iOS programming and tried to figure out what loadHTMLString:baseURL: really does, but I can't find a satisfying explanation. The site of Apple just says:
Sets the main page content and base URL.
Can someone please explain this in a more detailed way to me?
I am pretty certain that the baseURL is used just like in regular web pages to properly load ressources that are referenced using relative links. Now the question is, how to set that base URL to a particular folder in the app directory.
This is how mainly content is loaded in a webView. either from a local html file or through a url.
//this is to load local html file. Read the file & give the file contents to webview.
[webView loadHTMLString:someHTMLstring baseURL:[NSURL URLWithString:#""]];
//if webview loads content through a url then
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]]]
- (void) loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
is used to load local HTML file, parameter string means content of html file, if your HTML file contains some href tag with relative path, you should set the parameter baseUrl with the base address of the HTML file, or set it nil.
NSString *cachePath = [self cachePath];
NSString *indexHTMLPath = [NSString stringWithFormat:#"%#/index.html", cachePath];
if ([self fileIsExsit:indexHTMLPath]) {
NSString *htmlCont = [NSString stringWithContentsOfFile:indexHTMLPath
encoding:NSUTF8StringEncoding
error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:cachePath];
[self.webView loadHTMLString:htmlCont baseURL:baseURL];
}
- (NSString *)cachePath
{
NSArray* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
return [cachePath[0] stringByAppendingPathComponent:#"movie"];
}
How can I have a local image loaded into a html page in a UIWebView that is called with
[self.webView loadHTMLString:htmlSourceCode baseURL:externPageUrl];
I know I can get the image by changing the baseURL. However, in my case, that is not possible.
I also tried doing it by adding file://pathToImage/myimage.png to the html, but that doesn't work without changing the baseURL.
Is there any way without having to handle the shouldStartLoadWithRequest method?
Just set the image src to the name of the image file, assuming it is in the same folder as the local HTML file.
I solved it by loading the image bytes into the html directly:
//retrieve image data, to embedd into the html as base64
NSURL *imgURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"myImage" ofType:#"png"] isDirectory:NO];
NSData *data = [NSData dataWithContentsOfURL:imgURL];
[htmlContent appendFormat:#"<div class=\"myCssClass\" style=\"background:url(data:image/png;base64,%#) no-repeat center center;\" ></div>",
[data encodeBase64] ];