How to load an HTML5 document that is part of the project? - ios

i am working on an iPhone app, in my project I added an HTML5 page that is a template, and have a webview and want to load it on viewdidload. I can't seem to be able to access it, I am trying this :
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains( NSAllApplicationsDirectory, NSUserDomainMask, YES ) ;
NSString *documentDirectory = [ documentDirectories objectAtIndex: 0 ] ;
NSString *longPath = [ documentDirectory stringByAppendingFormat:#"/%#" filename ] ;
I am a bit confused? How can I achieve this? do I need to tell xcode that this html5 needs to be built and sent to a specific folder at runtime? like treated as a resource?
I am new to xcode coming from a .NET environment, so maybe the terminology is a bit awkward.
Thanks

If it's part of the project it won't be in the documents directory it'll be in your application bundle. For example:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:filename ofType:#"html"]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:req];

Related

How to load the html file with pdf on iOS WKWebView

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);

Load Multiple Cordova Micro Apps inside Native IOS apps

I have to load multiple cordova apps based on user access in Native IOS app.
I want to load the zip files dynamically on app launch and store them in Documents or Libraries folder and then unzip these files, then I'm trying to load cordova views directly using below code in my view controller
CDVViewController* viewController = [CDVViewController new];
viewController.wwwFolderName=#"www";
viewController.startPage=#"abc.html";
viewController.view.frame=CGRectMake(0, 0, 320, 480);
[self.view addSubview:viewController.view];
But the problem is that the wwwFolderName is not working if I point dynamically to Documents or Library folder it only accepts root folders which are shipped with the app, so I want to know how should I achieve this use case.
If I understood you correct, here is an example, where YOUR_APP_PATH is string path to the directory, where you want to store you application sources, and YOUR_SEARCH_PATH is NSLibraryDirectory or NSDocumentsDirectory
- (void)openApp
NSString *filePath = [self directoryToApp:YOUR_APP_PATH forSearchPath:YOUR_SEARCH_PATH];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL: url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 20.0];
[self.webView loadRequest:appReq request;
}
- (NSURL *)directoryToApp:(NSString *)appPath forSearchPath:(NSSearchPathDirectory)searchPath{
NSString *basePath = [self applicationDocumentsDirectory:searchPath].absoluteString;
return [NSURL fileURLWithPath:[basePath stringByAppendingString:appPath]];
}
- (NSURL *)applicationDocumentsDirectory:(NSSearchPathDirectory)searchPath
{
return [[[NSFileManager defaultManager] URLsForDirectory: searchPath
inDomains: NSUserDomainMask] lastObject];
}
let your wwwFolderName be following:
viewController.wwwFolderName=[NSString stringWithFormat: #"file://%#/www", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
this will point the start directory to your www folder inside document directory.

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]];

Load Image from UIwebview fail

I am using Webview to load a image file stored in my app Library Directory, first i tried use resourcePath, and bundle path
NSString * html = [[NSString alloc] initWithFormat:#"<img src=\"file://%#\"/>", filename];
[self.webView loadHTMLString:newhtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
the problem is no matter what i set in the baseUrl, i can not load the image correctly , i also tried filePath:
[self.webView loadHTMLString:newhtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] filePath]]];
but if i set the absolute path of the image file in the html , all the things is ok, i wonder why?
Have a look at this post: Using HTML and Local Images Within UIWebView
The top answer clearly said that using file: paths to refer to images does not work with UIWebView.
All you need to do is to pass the basepath. Example:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Then just need to reference it like this: <img src="myimage.png">

iOS 6 - Able to save .pdf from URL, able to display it in a WebView, NOT able to move it to iBooks

This is what I'm trying to do:
Get a .pdf from external URL
Save it into my local disk
Display it in a WebView
Allow the user to move the .pdf to another app who can read .pdf
Everything from 1 to 3 works fine. But nothing is moved/shared to/with other apps. I can't understand what I'm doing wrong. This is what I'm doing.
How I save the pdf in the Documents folder (viewDidLoad):
// to save the pdf into local file system (tempString is the pdf url)
NSData *pdfData = [[NSData alloc]
initWithContentsOfURL:[NSURL URLWithString:tempString]];
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePAth atomically:YES];
// to populate the WebView
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[my_web_view setUserInteractionEnabled:YES];
//[editoriale_view setDelegate:self];
[my_web_view loadRequest:requestObj];
In my viewDidLoad() function I create a button to allow the user to open a list of apps who can read .pdf files:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self
action:#selector(show_Button)];
And here's my show_Button function:
-(void)show_Button {
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath
stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
When I try this on my device everything works fine until I tap on one of the icons in the list (i.e. the iBooks one). Then the app closes (it doesn't crash, it simply closes).
Here's what the console prints for the two logs I put in the show_Button function:
1. filePath = /Users/[MY_USER]/Library/Application Support/iPhone
Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
2. url2 = file://localhost/Users/[MY_USER]/Library/Application%20Support/
iPhone%20Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
Anyone wants to try to make me understand what I'm doing wrong? I'm using Xcode 4.6. I browsed my iPhone app file system with a third-party software and the file "MyPDF.pdf" actually IS in the Documents" folder, and that's clear because the WebView is correctly populated.
Change CGRectZero to self.view.bounds when you display the document controller.
Solved. I had not implemented the UIDocumentenInteractionController delegate in the .h file. Now I have and everything works fine. Thank you to #trojanfoe for the useful hint.

Resources