How to load localized html file from WKWebView? - html

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

Related

How to show only section of site in UiWebView?

I want to show site in UiWebView but I don't need to show all site but only from <section id="xxx"> to </section> with optional <head> for CSS styles. I tried to download html code and paste it to UiWebView
NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://example.com/page"] encoding:NSUTF8StringEncoding error:nil];
NSString* content2 = string;
NSString* beforeBody = #"<section id=";
NSString* afterBody = #"</section>";
NSString* finalContent = [[beforeBody stringByAppendingString:content2]
stringByAppendingString: afterBody];
[_webView loadHTMLString:finalContent baseURL:nil];
but it didn't work for me. Any ideas? Thank you for help!
You can do the following:
Create 2 UIWebViews in your viewController, webView and webView2, implement #interface ViewController : UIViewController <UIWebViewDelegate> in your viewController header.
In viewDidAppear you will load the fullHTMLString from the page you would like to work with into webView2 and afterwards set the delegate for webView2 like so:
-(void)viewDidAppear:(BOOL)animated
{
NSString *fullHTMLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"https://python.org"] encoding:NSASCIIStringEncoding error:nil];
[self.webView2 setHidden:YES];
[self.webView2 loadHTMLString:fullHTMLString baseURL:nil];
[self.webView2 setDelegate: self];
}
You will have to implement webViewDidFinishLoad delegate method, and in it you call for [stringByEvaluatingJavaScriptFromString], which will retrieve your desired single element based on parameters you give it.
In this example I chose to retrieve it by ElementID, you can use javascript to retrieve it in other ways.
Once you have your desired element to display, you create an HTML string and insert it into it, afterwards you load the full html with the single element into the first webView (webView and not webView2) this is done to prevent an endless loop while calling the delegate method.
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *singleElementString = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementById(\"mainnav\").innerHTML;"];
NSString *html = [[NSString alloc] initWithFormat:#"<html>%#</html>", singleElementString];
[self.webView loadHTMLString:html baseURL:nil];
}

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.

Loading local html from an array in xcode

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

iOS - Showing App version in HTML page

I'm showing About in form of html in my iOS application. About.html is also bundled along with the application.
I want to show the application version in About html page automatically so that I dont have to edit the HTML manually everytime I bump the version.
Currently what I'm doing is as below:
I'm creating the html as <b>Version %#</b>
In Objective C code, I'm writing it as
NSString* aboutFilePath = [[NSBundle mainBundle] pathForResource:#"About" ofType:#"html"];
NSString* htmlStr = [NSString alloc] initWithContentsOfFile:aboutFilePath encoding:NSUTF8StringEncoding error:nil];
NSString* formattedStr = [NSString stringWithFormat:htmlStr, [self appNameAndVersionNumberDisplayString];
[self.webView loadHTMLString:formattedStr baseURL:nil];
- (NSString *)appNameAndVersionNumberDisplayString {
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *appDisplayName = [infoDictionary objectForKey:#"CFBundleDisplayName"];
NSString *majorVersion = [infoDictionary objectForKey:#"CFBundleShortVersionString"];
NSString *minorVersion = [infoDictionary objectForKey:#"CFBundleVersion"];
return [NSString stringWithFormat:#"%#, Version %# (%#)",
appDisplayName, majorVersion, minorVersion];
}
Is it good way to do it or is there any better way to achieve it?
You are doing it in near to perfect manner. There is no problem in proceeding with your approach.
That's ok. If you want to localise the text in the future then that might change the order of the parameters in the text so using something more like SUB_VERSION as the identifier to be replaced and then using the string replacement methods (instead of format method) would be better.

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