I want to use UIWebview in different view controllers,but i don't want these view controller to reload the web page, in another way, I want a UIWebview to load the page once,and used it anywhere.
SO I want to create a web view and load the webpage in a singleton way.
My question is : is this possible or appropriate?
Thanks a lot.
What's type of your html to present ? Is it static HTML content or dynamic URL source?
For static HTML content
I suggest you to create prefer HTML file and load them directly.
NSString *htmlContent = #"Your Static HTML Code";
NSData *htmlData = [htmlContent dataUsingEncoding:NSUTF8StringEncoding];
if (htmlData) {
NSString *_path = [[NSBundle mainBundle] bundlePath];
NSURL *_baseURL = [NSURL fileURLWithPath:_path];
[self.BottomWebView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:_baseURL];
}
For dynamic HTML content base on your URL source
When you have loaded the data in the first request , you can store them with NSData that can be the properties in your singleton class. Of course, you can call them any where, any ViewController to get your data and load them in your UIWebview with once connection.
hope it helps you !
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);
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!))
iOS 7 allows an NSAttributedString to be initialized with an HTML file or data. I want to use this functionality to make it easier to insert links in 'About' texts of apps.
To achieve this, I initialize the NSAttributedString with the following code:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"test.html" withExtension:nil];
NSError *error = nil;
NSDictionary *options = nil;
NSDictionary *attributes = nil;
_textView.attributedText = [[NSAttributedString alloc] initWithFileURL:url options:options documentAttributes:&attributes error:&error];
and a file with the following content:
<html><body>
<p>This is a test link. It leads to StackOverflow.<p>
</body></html>
Update
The above HTML still had the escape marks from trying to use it in code as an NSString. Removing the escapes makes it work just fine. Also answered my own question below.
End update
This works fine, and gives a string with the url properly formatted and clickable. Clicking the link calls the UITextView's delegate -textView:shouldInteractWithURL:inRange: method. However, inspecting the URL parameter shows the URL actually has the following absolute string:
file:///%22http://www.google.com/%22
which obviously doesn't open the appropriate webpage. I don't find the documentation on NSAttributedText clear enough to determine why this happens.
Anyone know how I should initialize the NSAttributedString to generate the appropriate URL?
Try reading the HTML file into a NSString and then use:
NSString *path = [[NSBundle mainBundle] pathForResource:#"test.html" ofType:nil];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
_textView.attributedText = [[NSAttributedString alloc] initWithHTML:html baseURL:nil options:options documentAttributes:&attributes];
At least this should work if it is similar with what happens in UIWebViews. The URL is resolved using the baseURL. It appears that in your code the source url is also used as baseURL. So I am passing a nil URL to prevent resolving against a local file URL.
The answer to this question is that the HTML file was invalid.
Having copy/pasted the html directly from a string defined in Objective-C, I forgot to remove the escapes before each quote. This of course translated directly to a file url instead of an HTML url. Removing the escape marks fixes this.
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
Since OS 3.0 UIWebView supports RTF files.
If you have a .rtf file, it's easy enough to load it into a uiwebview, e.g.
NSString *path = [[NSBundle mainBundle] pathForResource:documentName ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
When loading HTML stored in a string variable, you can use loadHTMLString.
How would one load RTF stored in a string directly into a UIWebView? For example, if you have a string containing {\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf360
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}....., using loadHTMLString will render it literally.
I would like to be able to render RTF from a string variable without having first to save it to a file.
Try loadData:MIMEType:textEncodingName:baseURL:. Haven't tried it, but it's worth a shot.