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!))
Related
In my project, I am using PDFJS library. I am loading a local pdf on UIWebView. But this occupies lot of RAM memory and at a point of time, its crashing. To avoid this, I want to use WKWebView.
In UIWebview, I am using like this (self refers to subclass of UIView)
UIWebView *uiWebview = [[UIWebView alloc] initWithFrame:self.frame];
[self addSubview:uiWebview];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"swift_tutorial" ofType:#"pdf"];
NSString *sPath = [[NSBundle mainBundle] pathForResource:#"viewer" ofType:#"html" inDirectory:#"PDFJS/web"];
NSString *finalPath = [NSString stringWithFormat:#"%#?file=%##page=1",sPath,filePath];
self.urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:finalPath]];
[uiWebview loadRequest:self.urlRequest];
When I print finalPath in the above snippet, the console output is /var/containers/Bundle/Application/DF419672-CF14-4B60-BE4F-EC0AC07C23AE/WebviewPOC.app/PDFJS/web/viewer.html?file=/var/containers/Bundle/Application/DF419672-CF14-4B60-BE4F-EC0AC07C23AE/WebviewPOC.app/swift_tutorial.pdf#page=1
In WKWebView, loadFileURL, loadHTMLString methods can be used to load local html file or a local pdf file, which works fine. But not both. For this html file, how to append the local pdf path and load in the WKWebView ?
Any help appreciated.
Let me answer my own question.
I have used WKWebViewLocal library for creating a localhost server.
Now, this will create access the local files via host name. Using this approach apps' memory utilization has been optimized a lot (Only because of WKWebView).
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"swift_tutorial" ofType:#"pdf"];
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:#"viewer" ofType:#"html" inDirectory:#"PDFJS/web"];
NSString *finalPath = [NSString stringWithFormat:#"http://localhost:8080%#?file=%##page=1",htmlPath, filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:finalPath]];
[self.webView loadRequest:request];
now, the finalpath will be
http://localhost:8080/~~~~~~~/PDFJS/web/viewer.html?file=/Users/~~~~~~/swift_tutorial.pdf#page=1
Because Apple will reject apps that use UIWebView API I had the same problem during moving from UIWebView to WKWebView. But since i'm using Xamarin framework i can't use WKWebViewLocal library. My solution is very similar.
First of all you need to add this code in OnElementChanged method in your CustomRenderer for WKWebView:
Control.Configuration.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("allowFileAccessFromFileURLs"));
It will grand access to files for this Control. Without it pdfjs won't be able to load documents and will always appear empty.
Then you need to change the code for reading files:
_pdfViewerAddress = (NSString)NSBundle.PathForResourceAbsolute("pdfjs/web/viewer", "html", NSBundle.MainBundle.ResourcePath);
if (UsePDFJS)
{
var pdfjsUrlString = $"file://{_pdfViewerAddress}";
var pdfjsUrl = new NSUrl(pdfjsUrlString);
var docUrlString = $"file://{GetDocumentUrl()}";
var docFolderUrlString = new NSUrl($"file://{Element.PathWithoutFileName}");
var finalUrl = new NSUrl($"{pdfjsUrl}?file={docUrlString}#page=1");
Control.LoadFileUrl(finalUrl, docFolderUrlString);
}
else
{
var error = new NSError();
var documentDirUrl = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, false, out error);
var dotsFolderUrl = documentDirUrl.Append("..", true);
var libFolderUrl = dotsFolderUrl.Append("Library", true);
var tempFolderUrl = libFolderUrl.Append("TemporaryFiles", true);
var fileUrl = new NSUrl($"file://{GetDocumentUrl()}");
Control.LoadFileUrl(fileUrl, tempFolderUrl);
}
In case of use pdfjs finalUrl should look like this:
file:///private/var/containers/Bundle/Application/80424409-E164-4409-A72B-43B32EC51F1A/iOS.app/pdfjs/web/viewer.html?file=file:///var/mobile/Containers/Data/Application/ED7233AE-8D10-41DC-8AF4-10662F14A883/Documents/../Library/TemporaryFiles/10850908.pdf#page=1
That's all. No external library needed. This also works if you want to open document from BundleResources. You can easily access it with this code:
(NSString)NSBundle.PathForResourceAbsolute("Guide", "pdf", NSBundle.MainBundle.ResourcePath);
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];
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.
I want to write html code locally and show it in UIWebview ,so for this ,I have taken a simple html code ,as below and created a .html extension file..
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
I added this file into my xcode project ,now I want to load this file inside webview ,so I have written this code
[m_websiteView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"test" ofType:#"html"]isDirectory:NO]]];
but the output I get when I run this code in UIWebView is same htmlcode, I cant figure out what the problem is..but when I tried using this code
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *testString = #"<h1><i>This is an image using reference in HTML</i></h1>"
"<img src='active.png'></img>";
[m_websiteView loadHTMLString:testString baseURL:baseURL];
this works perfect.also I want to localize the strings in this html code,so in the above code,how can I localize this string "This is an image using reference in HTML"..
Regards
Ranjit
Add localization, use this
NSString *testString = [NSString stringWithFormat:
#"<h1><i>%#</i></h1><img src='active.png'></img>",
NSLocalizedString(#"This is an image using reference in HTML", #"htmlText")];
and specify the localize strings in the file Localizable.strings in the correct language directory.
You can also localized entire (HTML) files with the locale directory scheme.
HTML syntax is
<html>
<head>
</head>
<body>
</body>
</html>
after that you can preview your html file using something like that in your view controller
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = #"http://www.istoselidas.gr";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];
just replace url with your html file
I've a problem that i couldn't solve, i wanna run the Apple - HTML5 Showcase - Gallary
in UIWebView inside my ipad app.
I've tried a local html file:
NSString *strr = [[NSBundle mainBundle] pathForResource:#"photo-gallery" ofType:#"html"];
NSString *str = [[NSString alloc] initWithContentsOfFile:strr encoding:NSASCIIStringEncoding error:nil];
NSLog(#"%#",str);
[webView loadHTMLString:str baseURL:nil];
and also a server html file, but it didn't work, can anyone help me, i wanna show an html5/css3 in UIWebView.
thx in advance.
hi this is what you can do
UIWebView *aWebView = [[UIWebView alloc] initWithFrame:webFrame];
//getthe path of the local html file
NSURL *baseURL = [NSURL fileURLWithPath:fileNamePath];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:baseURL];
//load the html file into the web view.
[aWebView loadRequest:aRequest];
//add the web view to the content view
[view addSubview:aWebView];
For server html you simply skip the second line, and put the address.
Hope it helps
You can take a look at phonegap. Its a complete framework for building html5 apps inside a UIWebview with native capabilities.
See: http://www.phonegap.com