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"];
}
Related
I was trying to display formatted text and did some research here on SO and ppl said to draw it with CG or use html and throw it in a UIWebView. As UIWebView being the easier option, I formatted my document in .html and dropped it into my folder like so:
Supporting Files/Data/Template.html
How do I access this file to show in a UIWebView?
I know I can get my documents by doing:
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
But after that, I'm stuck. I'm not sure how I would access my Template.html. Thanks
Assuming that you already have the NSURL to the offline template.html file.
NSURLRequest * offlineRequest = [NSURLRequest requestWithURL:offlineURL];
UIWebView * webview = [[[UIWebView alloc] init] autorelease];
[webview loadRequest:offlineRequest];
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:
can anyone tell how to add html in my iphone project??
And their is no html option which i click on add new file in class group...why is that???
simply create a blank file and rename it to html or add existing html file to the project.
the next step depends on how you wish to use the html file.
Say if you want to load a local file called page.html, first you add the file to project,and in the build phases of your project, and the page.html to Copy Bundle Resources, and run this in your app, it writes the file to the documents dictionary of your app/
NSString *Html = [[NSString alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"page" ofType:#"html"] encoding:NSUTF8StringEncoding error:NULL];
[Html writeToFile:[[self docPath]stringByAppendingPathComponent:#"page.html"] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
[Html release];
and your webview should call this to load the file:
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [docPaths objectAtIndex:0];
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[docPath stringByAppendingPathComponent:#"page.html"]]]];
and it's done.
What you might be looking for is documentation and example code for the UIWebView class of UIKit.
You can use UIWebView to show your html file like this
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
[webView loadRequest:request];
where URLString contains is your file url.
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]]];
Greetings! Can anyone please kindly assist me finding a way around the following:
load an html into a UIWebView using loadHTMLString and include(using baseURL) the resources such as the CSS, image files from folders within user's Documents directory - and not from the MainBundle of the application.
I have seen tutorials on how to use baseURL to load within the application bundle/MainBundle which is straightforward but not with resources from the iPhone's Documents directories.
The structure of my documents folder is as follows:
dirX
|---> file.xml
|---> dirCSS
|---> style.css
I can retrieve the full path to the dir X(Users/......./dir X). However, when passing that path to the UIWebView's baseURL such that
[webView loadHTMLString:fileXMLString baseURL:pathToDirX]
... webView does not recognize the resources(eg style.css within dirCSS) as href'ed within the fileXMLString
<link href="dirCSS/style.css" rel="stylesheet" />
So currently my application can successfully load the html string but does not load the stylesheet as the link to the CSS within the html string are relative - eg. css/style.css
Any help is very much appreciated :)
After some googling I have finally found a fitting solution for the question I posed. Hopefully this would help those who face the same problem.
The trick is with the formatting of the string path when creating an NSURL object for baseURL of a UIWebView. Although usually I use the typical "Users/...../dir/file" in most cases, loading using UIWebView's loadHTMLString:baseURL needs a different approach.
As described in http://dblog.com.au/iphone-development/loading-local-files-into-uiwebview/, where I got the solution, string path to the resources just needs to have slashes to be replaced with double-slashes and spaces with %20:
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *HTMLData = #"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:
[NSURL URLWithString:
[NSString stringWithFormat:#"file:/%#//",imagePath]
]];
Do take note of the replacing of the strings and also the:
[NSString stringWithFormat:#"file:/%#//",imagePath]
Although the example code above is retrieving the path to the mainBundle of the application, it can also work in other folders, ie Documents(and its subfolders) as I did in mine.
Kind regards,
oonoo
PS Thanks again Nic for the reply :)
To get the path to the document directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"index.xml"];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]
The easiest way to have everything working, is to simply load your index.html from the document directory instead of loading a string. Otherwise set the baseUrl to the document directory.
// call this method and set the directory , Currently it is cache directory . If you want document directory then change NSCacheDirectory to NSDocumentDirectory
-(NSString*)getBasePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES);
NSMutableString *cacheDirectory = [NSMutableString stringWithString:[paths objectAtIndex:0]];
[cacheDirectory appendString:#"/"];
NSRange renge= NSMakeRange(0, cacheDirectory.length);
[cacheDirectory replaceOccurrencesOfString:#"/" withString:#"//" options:NSCaseInsensitiveSearch range:renge];
renge= NSMakeRange(0, cacheDirectory.length);
[cacheDirectory replaceOccurrencesOfString:#" " withString:#"%20" options:NSCaseInsensitiveSearch range:renge];
[cacheDirectory insertString:#"file://" atIndex:0];
//file:////Users//hb//Library//Application%20Support//iPhone%20Simulator//6.0//Applications//3A141D33-390A-4DD2-8825-7DDC07D29894//Library//Caches//
return cacheDirectory;
}