Loading local html from an array in xcode - html

I am attempting to load a locally hosted html file into a webview from an array. it looks something like this
_siteAddresses = [[NSArray alloc]
initWithObjects:#"file://localhost/var/mobile/Application/${APP_ID}/First Pentecostal Seminary.app/First_Pentecostal_Seminary/Main.html",...
with the corresponding code being
NSString *urlString = [_siteAddresses
objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.detailViewController.webView.scalesPageToFit = YES;
[self.detailViewController.webView loadRequest:request];
What am I doing wrong...is it my coding or perhaps the html coding (I believe there may be some java in there)

Two thoughts:
That example file URL doesn't look right. How did you construct that? If it was something from your bundle on your device, I'd expect something more like:
file:///var/mobile/Applications/9E670C3C-C8B1-4B09-AE66-B43F7DB29F4D/First Pentecostal Seminary.app/...
Obviously, you have to programmatically determine this URL by using NSBundle instance method URLForResource or by using the bundle's bundleURL and then adding the appropriate path components.
You should (a) specify the view controller to be the delegate for your web view; and then (b) implement webView:didFailLoadWithError: and look at the error there, and it will inform you what the error was, if any.
For example, I have a file, test.html sitting in my bundle, which I can load into a web view like so:
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSURL *url = [bundleURL URLByAppendingPathComponent:#"test.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
I have set up my view controller as the delegate for the web view and have the following didFailLoadWithError:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"%s: %#", __FUNCTION__, error);
}
So, when I tried to load a request with an invalid URL this time (test2.html, which I do not have in my bundle), I get the following error:
2014-02-26 23:35:43.593 MyApp[3531:70b] -[ViewController webView:didFailLoadWithError:]: Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo=0x8c32f40 {NSErrorFailingURLStringKey=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF/MyApp.app/test2.html, NSErrorFailingURLKey=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF/MyApp.app/test2.html, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x10424c90 "The requested URL was not found on this server."}

Try this code
UIWebView *documentsWebView=[[UIWebView alloc]init];
documentsWebView.delegate=self;
documentsWebView.frame=CGRectMake(0, 0, 1024, 616);
documentsWebView.backgroundColor=[UIColor clearColor];
[self.view addSubview:documentsWebView];
NSString* htmlString = [NSString stringWithContentsOfFile:[_siteAddresses
objectAtIndex:indexPath.row] encoding:NSUTF8StringEncoding error:nil];
[documentsWebView loadHTMLString:htmlString baseURL:nil];

Related

How to load localized html file from WKWebView?

1st StackOverflow question for me...
!! Objective-C !!
I'm in the process of updating an old app and am working on help screens.
I chose to display some useful How-tos through some html mainly for the ease of formatting the text (bullet points, colors, bold, underline etc...).
Since the app is a bit complex, The help screens are in a total of 3:
A main info webpage that links to 2 other detailed pages.
Tha app is localized in English (Base) and French.
Once the setup was complete, and with everything working fine, I went ahead and localized the base html files.
Now, they are neatly placed in the Base.lproj and fr.lproj files.
But when when I tap on a link to another page from the main WebView, nothing happens !
Any ideas ?
Thanks
Here are some bits of code I'm using:
In the .h file :
#interface howToViewController : UIViewController <WKUIDelegate>
{
WKWebView *infoText;
NSString *uRLString;
}
#property (nonatomic, retain) WKWebView *infoText;
In the .m file: (had to programmatically create the WKWebView because of the known Xcode 9 bug when creating it through Storyboards)
- (void)viewDidLoad
{
[super viewDidLoad];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *aWebView = [[WKWebView alloc] initWithFrame:self.view.frame
configuration:theConfiguration];
aWebView.UIDelegate = self;
self.infoText = aWebView;
NSURL *url = [[NSBundle mainBundle] URLForResource:#"infoHTML" withExtension:#"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[infoText loadHTMLString:html baseURL:baseUrl];
[self.view addSubview:infoText];
}
In the html file, the links that no longer work once the files are localized:
<p>3/ More information is available for the respective tabs by pressing the following links :</p>
<ul><li>Limitations
</li></ul>
<ul><li>Fueling
</li></ul>
Working code from one of my apps. I'm using NSURLRequest and WKWebView's loadRequest instance method. I'm not sure what's going wrong with your use of loadHTMLString:baseURL: but I think it may have something to do with the value you're passing for the baseURL argument. Have you cleared the console, then single-stepped over that line of code to see if you're getting any message in the console?
NSURL *url = [[NSBundle mainBundle] URLForResource: pageString withExtension: #"html"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
[webView loadRequest: request];

How to show an image saved on Documents Directory inside local HTML? iOS

I've this app which needs to store images shown in a webview locally, and show those stored images again inside the same webview.
This what I've gotten so far...
// After download button clicked... Store image from URL locally
NSURL *url = [NSURL URLWithString:myURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
// Get image path from Documents Directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"filename.png"];
// Display local html page
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"revistasPhotoswipe" ofType:#"html" inDirectory:#"www"]];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView loadRequest:requestObj];
And in html file there's just a tag to show the image
<html>
<head></head>
<body><img src='filename.png' /></body>
</html>
Which is the right way to communicate the Documents Dir, with App Bundle and the HTML files to make this work? Another approach?
You can't use <body><img src='filename.png' /></body> because it references an object on a localserver that doesn't exist. You have a couple of options:
1. Javascript
A milliseconds after the page has loaded you should tell your webview to evaluate a javascript function.document["pictureIdFromProgam"].src = searchPic.src; as well as declaring your image element with <img src='throw.imgNotSet' id='pictureIdFromProgam'/>
2. String Manipulatoin
Another (less desirable, but quicker) option is to have your HTML file coded into an NSString and inserting the img link by using either replacing or %#s
Insertion:
[NSString stringWithFormat:#"<html><blah blah blah/><img src=%#/>",imagePathAsString];
and then you will be able to tell your webview to load the nsstring which contains the updated web content.

WKWebView Could not create a sandbox extension for '/'

I would like to use external file .html to use WKWebView. Or is there a solution without external file ? All is working good on simulator, but not on device...
Here is my code :
NSString *path = [[NSBundle mainBundle] pathForResource:#"myHTML" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
WKWebViewConfiguration *theConfiguration =
[[WKWebViewConfiguration alloc] init];
[theConfiguration.userContentController
addScriptMessageHandler:self name:#"interOp"];
_webView = [[WKWebView alloc] initWithFrame:self.view.frame
configuration:theConfiguration];
[_webView loadRequest:request];
[self.view addSubview:_webView];
I've read this topic : WKWebView not loading local files under iOS 8
I don't want to use a server. I'm using Objective-C, and I want that it works on only one view, not like the https://github.com/shazron/WKWebViewFIleUrlTest project with 2 views and button and I need to have connexion with internet in the page (read iFrame).
What have I to do ?
You have to copy all your web files to the app's NSTemporaryDirectory and call your index.html from there. Works fine on iOS 8.3 for me.

Delete Cache with UIWebview in an iOS application

I have a problem with UIWebview. I call several time an url for print a pictures in my webview and I count how many times my pictures was displayed.
When I call the url of the pictures the count match to the number of printing.
NSURL *URL = [NSURL URLWithString:#"http://url_pictures.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[adView loadRequest:request];
When I call the url with loadhtmlstring my counter is to one. It's very important for me to use loadhtmlstring because my API returns me a html code with javascript.
NSString *html = #"<html><head></head><body>document.write(\"<a target=\"_blank\"ref=\"http://url_redirect.com\"><img border=\"0\" src=\"http://url_pictures.com\"></a>\");</body></html>";
NSString *baseURL = [mbAdUtil getBaseURL:html];
NSString *script = [[NSString alloc] initWithFormat:#"%#", html];
[adView loadHTMLString:script baseURL:[NSURL URLWithString:baseURL]];
I tested a lot of things that my counter is egal to printing.
this is some example of what I tested :
[webView loadHTMLString:#"" baseURL:nil];
[webView stopLoading];
[webView setDelegate:nil];
[webView removeFromSuperview];
Another :
// remove all cached responses
[[NSURLCache sharedURLCache] removeAllCachedResponses];
// set an empty cache
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
// remove the cache for a particular request
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
Also, I tested by destroying my instance of my project and create another.
I destroyed my webview, all my variable... and so much else that I can not remember.
My counter is always 1.
My better solution is :
[webView loadHTMLString:#"" baseURL:nil];
[webView stopLoading];
[webView setDelegate:nil];
[webView removeFromSuperview];
With this I count 2 to 3 printing but the visual result is not that I expect.
Add cache policy on NSURLRequest:
NSURL *URL = [NSURL URLWithString:#"http://url_pictures.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[adView loadRequest:request];
there three policy that will most likely help your solution:
NSURLRequestReloadIgnoringLocalCacheData,
NSURLRequestReloadIgnoringLocalAndRemoteCacheData,
NSURLRequestReloadIgnoringCacheData
I solved my problem !
I remove all my tests and I added timestamp has all level :
NSString *html = #"<html><head></head><body>document.write(\"<a target=\"_blank\"ref=\"http://url_redirect.com?time = 123456789\"><img border=\"0\" src=\"http://url_pictures.com?time = 123456789\"></a>\");</body></html>";
NSString *baseURL = [mbAdUtil getBaseURL:html];
it same as if there were several level cache. It's very stange but it works...
My solution is :
if http://url_redirect.com or http://url_pictures.com call another url, we must add the timestamp for me.

How would you create a new local HTML file into a UIWebView on iOS?

First I would like to point out I'm very new to web development and more comfortable with iOS development, so excuse me if there's something fundamental I'm not understanding.
I've seen how you can place an HTML file into your apps directory and load it into a web view (Example). This is great, but how can you create a new local HTML file within the app? Such that the user can create a new html file to type in, and then store it (basic document style app functionality). Perhaps with some sort of Javascript (I'm not too familiar with such Javascript)?
You can build the HTML in a NSString like so:
// get user input
NSString *userText = #"Hello, world!";
// build the HTML
NSString *html = [NSString stringWithFormat:#"<html><body>%#</body><html>", userText];
// build the path where you're going to save the HTML
NSString *docsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filename = [docsFolder stringByAppendingPathComponent:#"sample.html"];
// save the NSString that contains the HTML to a file
NSError *error;
[html writeToFile:filename atomically:NO encoding:NSUTF8StringEncoding error:&error];
Clearly I'm just setting the userText to some literal, but you could obviously let the user type it into a UITextView and grab it from there.
You can then load the HTML into a web view with:
[self.webView loadHTMLString:html baseURL:nil];
or with:
NSURL *url = [NSURL fileURLWithPath:filename];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];