How to append javascript into UIWebView in iOS? - ios

I'm trying to change Font in UIWebView.
I tried with the following codes to change Font.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *cssPath = [path stringByAppendingPathComponent:#"test.css"];
if(!cssPath)
{
NSLog(#"NO");
}
NSString *js = [NSString stringWithFormat:#"var cssChild = document.createElement('link');"
"cssChild = 'text/css';"
"cssChild = 'stylesheet';"
"cssChild = '%#';", cssPath];
js = [NSString stringWithFormat:#"%# document.getElementsByTagName('head')[0].appendChild(cssChild);", js];
[webViewOfInitial stringByEvaluatingJavaScriptFromString:js];
I append css file into header of loaded page from internet.
my css file is following like that.
#font-face {
font-family: 'Zawgyi-One';
font-style: normal;
src: local('Zawgyi-One');
}
body {
font-family: 'Zawgyi-One';
}
However when i retrieve html tags when finished page loaded , i can't find my above css tags.
So how do i append that css file into current page of UIWebView's header tags?
Or is there any others tutorials for UIWebView Font change?
Thanks.

You are going in the right direction but you haven't mentioned , which delegate method you are trying to make changes in.
you can have your javascript in a .js file as you might make changes to it later and it will be really cumbersome to reflect the changes through code (instead of a js file).Try Using this :-
you have to load the HTML into the view with the correct baseURL parameter to use relative paths or files in UIWebView.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
baseURL accepts an NSURL object as the file reference.You can specify a local URL or a web one as your needs leads you to.Append the css file in webViewDidFinishLoad:(UIWebView *)webView as you have done.
NOTE:-Select the .js file and uncheck the bullseye column indicating it as compiled code.(You will just get a warning if you don't).
Here's aUIWebview Javascript Tutorial that might get you going.

Related

HTML Link from within a local HTML file in a UIWebView

Very new to XCode here
Basically, we have an app dependent on the UIWebView. When there is a valid network connection, we load a mobile web page into the UIWebView, if there is no connection, we will load a local version of the html web page. My scenario has to do with the offline or limited network connection scenario. When this offline scenario does occur, I am able to load my local html file just fine using the answer from this thread:
Load resources from relative path using local html in uiwebview
My problem comes in when click on a simple html link (which is also within my local app directory) within the local html file that is loaded. I have tried these, but when I click the link, nothing occurs, the link does not take me anywhere and the simulator will only allow me to copy the text:
<a href="file:///Sample.html">
<a href="file://Sample.html">
<a href="Sample.html">
<a href="/Sample.html">
<a href="Testing/Sample.html">
The sample.html webpage is in the same directory as the initial loaded html page. Not sure where I am going wrong, obviously missing something simple.
I suggest you re-examine your directory hierarchy. The behavior you are describing is what happens when the link you are trying to navigate to does not exist on the local device.
I ran the following small test:
Added a Webview to a view controller and loaded page1.html
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 10, 320, 300)];
[self.view addSubview:webView];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"page1" withExtension:#"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:html baseURL:baseUrl];
page1.html
<html>
<body>
<h1>Page 1</h1>
Go to Page2
</body>
</html>
page2.html
<html>
<body>
<h1>Page 2</h1>
Back to Page 1
</body>
</html>
Image of the project Structure
The end result is, that it works. Clicking takes you from page 1 to page 2 and back again all using local files. If we change the link to:
which does not exist, you get the same behavior you are experiencing. That is you can only cut and copy and not actually go to the link.
For using resources from local file system try this solution like I did for displaying image on WebView.
-(NSString *)imagePath:(NSString *)fileName
{
if ([fileName isEqualToString:#""] == NO) {
NSLog(#"%#",fileName);
NSString *ImagePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"png"];
ImagePath = [ ImagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
ImagePath = [ ImagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
ImagePath = [#"file://" stringByAppendingString:ImagePath];
return ImagePath;
}
else
{
return #"";
}
}
Just assume you wnat to return the full path of your save HTML pages.
#Chris has an excellent example laid out, may be we need to update as follows :
let webView = UIWebView(frame: self.view.frame)
webView.delegate = self
self.view.addSubview(webView)
let urlString = Bundle.main.url(forResource: "Page1", withExtension: "html")
webView.loadRequest(URLRequest(url:urlString!))

How can I add a image into uiwebview

In iOS, I need to load a website in uiwebview and I want to add a local image at the beginning of the webpage.
I added < img src="logo.png"/> after < body > tag but it only showed a null pic(a small white box).
How can I load my local image as the src of the img inside the html? Thanks
Using relative paths or file: paths to refer to images does not work with UIWebView. Instead you have to load the HTML into the view with the correct baseURL:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
You can then refer to your images like this:
(from uiwebview revisited)
You have to define the extact path of the image source see code below
NSString *imagePath=[[NSBundle mainBundle] pathForResource:#"image" ofType:#"png"];
imagePath=[NSString stringWithFormat:#"file://%#",imagePath];
NSString *html=[NSString stringWithFormat:#"<html><body><img src=\"%#\"/></body></html>",imagePath];
[webView loadHTMLString:html baseURL:nil];
Cheers.

Loading html file in UIWebvView called 'index.html?mod=eurt'

Let me start by saying I know how to load up an html file, but I need to load up index.html?mod=eurt. So the file itself is called index.html, but I need to load it with ?mod=eurt at the end. (the html file is shared between different applications and changing "?mod=X", will tell the file exactly what to do.
The problem is, I cannot figure out how to do this with the way I am loading up the html into the webview (I'm rather new at iOS development, so there may exist an easy way I don't know about). Here's what I have to load a local html file so far:
NSString *htmlFile=[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"
inDirectory:nil];
NSString *htmlString=[NSString stringWithContentsOfFile:htmlFile
encoding:NSUTF8StringEncoding error:nil];
[webView loadHtmlString:htmlString baseURl:nil];
I tried changing the ofType:#"html" to ofType:#"html?mod=eurt", but I didn't really expect that to work, and it didn't.
I've come from the land of Android where I simply did webView.loadUrl("file:///android_asset/index.html?mod=eurt");
There must be an easy way to do this in iOS, right?
You can do something like this
NSString* bundlePath = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSString* strUrl = [[urlToLoad absoluteString] stringByAppendingString:#"?mod=eurt"];
NSURL* urlToLoad = [NSURL URLWithString:strUrl];
[webView loadRequest:[NSURLRequest requestWithURL:urlToLoad]];

UIWebview not fetching the linked CSS resource

I am trying to load a local html content into uiwebview. I already have the html content ready with me, and i am adding a reference a online css file to the content by the mechanism as shown in the code below. However, the problem i am facing is when i load the webview, there is no styling. Also, I verified in the Charles Proxy, there is no outgoing call for fetching iphone.css file to my base server. Ideally, while loading a html page, uiwebview should get all the referred resources, but for some reason unknown to me, it is not fetching the css file.
Please review and let me know if there is some issue with my code that i am not able to identify here?
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><link type=\"text/css\" href=\"http://<base_server>/resources/iphone.css\" /><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body>%#</body></html>";
UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
NSLog(#"%#",[NSString stringWithFormat:htmlString,entry.body]);
[webview loadHTMLString:[NSString stringWithFormat:htmlString,entry.body] baseURL:[NSURL URLWithString:#"http://<base_server>/"]];
[self addSubview:webview];
It's hard to tell if there are any typos in the HTML with all of the double quote escaping going on in that string. Why don't you pull the HTML out of the string and into a file, read that file in and place your content in the body. There may be a mistake with the markup in that string. This would allow you to read it easier in a seperate file.
Something like:
NSError *error;
NSStringEncoding encoding;
NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource: #"Sample"
ofType: #"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFilePath
usedEncoding:&encoding
error:&error];
NSString *html = [NSString stringWithFormat:htmlString, entry.body];
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webview loadHTMLString:html baseURL:baseURL];

ios - printing HTML from a .html file not working in a UIWebView

I got "hello world" text to print after I hardcoded some html right into my UIWebView functions, but now I am trying to move that HTML to a file elsewhere on the file system, and it isnt rendering.
Here is what I have:
- (void)viewDidAppear:(BOOL)animated
{
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"learn" ofType:#"html" inDirectory:#"src/html_files"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[theWebView loadHTMLString:htmlString baseURL:nil];
}
and my HTML file is in a directory that I made called src/html_files and the file is named learn.html
What am I doing incorrectly that the HTML is not rendering on the screen?
Thank you!
Ok, so Groups are just a construct in Xcode for keeping your app's resources organized. Although Xcode uses the little folder icon, it doesn't necessarily mean those are actually separate folders on the (Mac or iOS) filesystem.
But, it sounds like you have added that file as a bundle resource. That's what the code you posted looks like, too, but I had to ask, to be sure.
Most likely, the only thing wrong is that this:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"learn"
ofType:#"html"
inDirectory:#"src/html_files"];
should be this instead:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"learn"
ofType:#"html"];
From the Apple documentation for NSBundle,
+ (NSString *)pathForResource:(NSString *)name
ofType:(NSString *)extension
inDirectory:(NSString *)bundlePath
bundlePath
The path of a top-level bundle directory. This must be a valid path. For example, to
specify the bundle directory for a Mac app, you might specify the path /Applications/MyApp.app.
The bundlePath parameter is not meant to specify relative paths to your bundle resources. The version of pathForResource:ofType: that does not have a bundlePath parameter is almost always what you'll use. It will find the learn.html file wherever it lives, once your app is installed, and return the full path to that. You don't really have to worry about how it's nested. It's just a bundle resource.
Give that a try. As I suggested in my comment, though, I always recommend taking advantage of the error parameter for debugging:
NSError* error;
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error: &error];
if (error != nil) {
NSLog(#"Error with stringWithContentsOfFile: %#", [error localizedDescription]);
}

Resources