I've read many of the existing questions and answers for my problem but none seem to answer it specifically and simply.
I am displaying many HTML files in my app and want to use a CSS to help format them. The CSS file will be held locally together with the HTML files.
I think I want to add the CSS ref inline - presuming that's then right way to do it?
My code is
- (void)viewDidAppear:(BOOL)animated {
[super viewWillAppear:animated];
[adviceContent loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:[advice objectForKey:#"HTML"] ofType:#"html"]
isDirectory:NO]]];
[super viewDidAppear:animated];
}
And I've inserted my CSS reference in the HTML file thus within the head tags <
link rel="stylesheet" type="text/css" href="photovaluesCSS_2column.css" media="screen"/>
Can someone explain where I'm going wrong?
Thanks
When loading the HTML, you need to specify a base URL for the css file, so your controller will "know" where that CSS file is located.
Here's a code that loads a html string which uses a css file. You can load the entire css from a file, or modify it as you need.
// HTML files are stored in the main bundle
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle bundlePath];
NSString *filename = #"none";
NSString *fullPath = [NSBundle pathForResource:filename ofType:#"html" inDirectory:path];
// load a HTML from a file
NSString *chapter_filename = [NSString stringWithFormat:#"Section%d", _chapter];
NSString *sectionHTMLPath = [[NSBundle mainBundle] pathForResource:chapter_filename ofType:#"html"];
NSString* htmlContent = [NSString stringWithContentsOfFile:sectionHTMLPath encoding:NSUTF8StringEncoding error:nil];
// add a generic template and the css file directive
NSString* htmlString = #"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"he\" lang=\"he\"><head><style type=\"text/css\" media=\"all\">#import \"styles.css\";</style><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body>%#</body></html>";
// load the html into a web view
NSURL *url = [NSURL fileURLWithPath:fullPath];
[_webView loadHTMLString:[NSString stringWithFormat:htmlString, htmlContent] baseURL:url];
Related
I have created a UIWebView and used a HTML file to display some contents. But when I run it instead of showing the contents only the whole HTML file coding is coming in the WebView. Please help and tell me what is wrong.
UIWebView *ingradients= [[UIWebView alloc]init];
[ingradients setFrame:CGRectMake(10, 170, 300, 300)];
[ingradients loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"htmlfile" ofType:#"html"]isDirectory:NO]]];
ingradients.delegate=self;
[self.view addSubview:ingradients];
My htmlfile.html contains
<html>
<body>
<p><strong>Ingredients</strong></p>
</body>
</html>
Instead of showing "Ingredients" in bold its showing the whole coding of htmlfile.html
In Your code you alway contain HTML code because your request always return file htmlfile with extantion .html
If you want to get specific value from HTML content you need to Parce HTML content by using Hpple. Also This is documentation with exmple that are use for parse HTML content.
In your case you use: (by using Hpple)
TFHpple *dataParser = [TFHpple hppleWithHTMLData:placesData];
// name of place
NSString *XpathQueryString = #"//p/strong";
NSArray *listOfdata= [dataParser searchWithXPathQuery: XpathQueryString];
That's weird, I have similar code for this and html is rendered as rich text but not as plain text (like you have), the only difference I have is using fileURLWithPath: but not fileURLWithPath:isDirectory:. Here's my code:
NSString *localFilePath = [[NSBundle mainBundle] pathForResource:#"about" ofType:#"html"];
NSURLRequest *localRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:localFilePath]];
[_aboutWebView loadRequest:localRequest];
Maybe you have some issues with file encoding, but as far as I guess, that should not be the case.
Try this code:
- (NSString *) rootPath{
return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
}
- (NSString *) pathFoResourse : (NSString *) resourseName ofType: (NSString *)type{
NSString *path = [[MMSupport rootPath] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", resourseName, type]];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
path = [[NSBundle mainBundle] pathForResource:resourseName ofType:type];
}
NSLog(#"**path:%#**", path);
return path;
}
- (void) loadDataToWebView : (CGRect) frame{
NSString *htmlString = [NSstring stringWithContentsOfFile:[MMSupport pathFoResourse:#"filename" ofType:#"html"] encoding:NSUTF8StringEncoding) error:nil];
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
[webView loadHTMLString:htmlString baseURL:nil];
}
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"];
}
I've got some HTML and some images in my iPhone app, arranged something like:
html/
foo.html
images/
bar.png
I can get bar.png to appear in my UIWebView a couple of different ways -- either loading foo.html from an NSUrl, and walking back up the directory tree from the html directory:
<img src="../images/bar.png"/>
or by loading foo.html into a string, using loadHtmlString, and using [[NSBundle mainBundle] bundleURL] as the baseURL:
<img src="images/bar.png"/>
Both of these are kind of clumsy, though -- in the first case, if I move HTML files around I have to rejigger all the relative paths, and in the second case, I have to ignore the actual path structure of the HTML files.
What I'd like to make work is this --
<img src="/images/bar.png"/>
-- treating the bundleURL as the root of the "site". Is there any way to make this work, or am I doomed to have that translated into file:///images/bar.png and have the file not found?
Only way I can see for you to do this would be to embed a web server in your app. Matt Gallagher has a blog post on this you could start from. Alternatively, CocoaHTTPServer and Mongoose could be dropped into your project.
If I'm not mistaken, you have some files in your project bundle that you want to load in your web view. You can do it simply with these few lines of code:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:#"bar" ofType:#"png"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
I'm assuming that you have a text/html file containing the pattern for your web view. You'll need to add the image as an object there (src="%#"...) and then add the imageURL to the pattern:
NSString *path = [[NSString alloc]initWithString:[[NSBundle mainBundle]pathForResource:#"htmlPattern" ofType:#"html"]];
NSError *error;
NSString *pattern = [[NSString alloc]initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
htmlPage = [[NSString alloc]initWithFormat:pattern,
imageURL;
webView = [[UIWebView alloc] initWithFrame:WEBVIEW_FRAME];
[webView loadHTMLString:htmlPage baseURL:[NSURL URLWithString:path]];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pattern]]];
Problem: I have a webview that is loading a page from Http://somerandomsite-here
before the page is loaded I would like to add in the <head> block a reference to a .js that is in my bundle.
How do I do that?
Found the answer by myself:
NSString *path = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[sourceWeb stringByEvaluatingJavaScriptFromString:jsCode];
in test.js place this code in a function that you'll call (see below)
Function setup() { var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "filename.js");}
when you think it's right do it for you particular case, call this:
NSString *setup = [NSString stringWithFormat:#"Setup()"];
[sourceWeb stringByEvaluatingJavaScriptFromString:setup];