Pass Variable (cookie) from local html to UILabel - iOS - html

I wanted to know how I could go about passing a Variable (cookie) in a local HTML file in my iOS App, and pass what the cookie says onto a UILabel. Here is what the HTML code is. I need to pass this message into a UILabel
<script language="javascript">setCookie('Test','You Sir have succeeded. Congratulations.', 300);
</script>
And here is my updated code for iOS app
Header File:
import
#interface ViewController : UIViewController {
IBOutlet UIWebView *webView;
IBOutlet UILabel *mylabel;
}
#end
Main File
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"DTPContent/cookietest" ofType:#"html"]isDirectory:NO]]];
[super viewDidLoad];
NSString *myCookie = [self->webView stringByEvaluatingJavaScriptFromString:#"getCookie('Test')"]; self->mylabel.text = myCookie;
}
#end
Thank You in Advance!

Assuming you already have a javascript function to get the cookies, like that, you can simply execute the javascript with webview's method stringByEvaluatingJavaScriptFromString , get it's returned string and set it in a UILabel.
It will be something like this:
NSString *myCookie = [self.webView stringByEvaluatingJavaScriptFromString:#"getCookie('Test')"];
self.mylabel.text = myCookie;

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

I am trying to Load html string into a webview. But the webview shows a white blank colour on run time

I am trying to Load html string into a webview. But the webview shows a white blank colour on run time. added the UIWebViewDelegate and declare object like this.
#property (strong, nonatomic) IBOutlet UIWebView *aboutWebView;
but still having the same issue.
- (void)viewDidLoad {
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:YES animated:YES];
[_aboutWebView setDelegate:self];
[self loadWebView];
// Do any additional setup after loading the view.
}
-(void)loadWebView{
_aboutWebView= [[UIWebView alloc]init];
_aboutWebView.backgroundColor= [UIColor blueColor];
NSString *embedHTML= #"html Code";
[_aboutWebView loadHTMLString: embedHTML baseURL: nil];
}
Please remove the below line from your code.It works for you.
_aboutWebView= [[UIWebView alloc]init];
Set the web-view delegate after initialising it , and add this line of code [webView setScalesPageToFit:YES];
There is no need for allocating your webview again in loadWebView method of yours.
comment this line "_aboutWebView= [[UIWebView alloc]init]".
You are already creating an IBOutlet for your webview which automatically creates an object for view.
Have below in HTML String
<head><style type='text/css'>body {background-color: transparent;border: 0px;margin: 0px;padding: 0px;}</style></head>
And for webview have this
yourWebView.backgroundColor = [UIColor clearColor];
yourWebView.opaque = NO;
This will not show white color in run time...
First at all,your HTML format is not correct,writing correct HTML to load on webView.
Then,add self.view.backgroundColor=[UIColor whiteColor]; in function - (void)viewDidLoad.
Hope to help you!

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

UIWebView opening the camera and images when a button is clicked

I am currently wrapping a webApp up as an app. With in the web app there is a button that when clicked automatically asks if you want to go to the camera of the stored images and when selected will upload the image for you. In the web app from the phone browser this works as expected.
Now I have wrapped the webApp up in a UIWebView this function no longer works. It actually appears to close the UIWebview when selecting either of the above options. Does anyone know what the procedure is to get this to work through the UIWebView.
Do I have to give permission? Or is there more to it like detecting the HTML when the button is clicked and handling it from the UIWebView.
The HTML on the button looks like this.
<input type="file" required id="file" name="file" accept="image/*" multiple>
ADDED CODE
WebViewController.h
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController <UIWebViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
UIViewController *viewController;
}
........
WebViewController.m
#import "WebViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "AppDelegate.h"
#end
#implementation WebViewController
- (void)viewDidLoad
{
[super viewDidLoad];
viewController = [[UIViewController alloc] init];
NSString *fullURL = self.mainURL; // get this from defualts - have removed code for this
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSLog(#"%i",[group numberOfAssets]);
} failureBlock:^(NSError *error) {
if (error.code == ALAssetsLibraryAccessUserDeniedError) {
NSLog(#"user denied access, code: %i",error.code);
}else{
NSLog(#"Other error code: %i",error.code);
}
}];
}
-(void)webViewDidStartLoad:(UIWebView *)viewWeb
{
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)webViewDidFinishLoad:(UIWebView *)viewWeb
{
}
//Note: I check to make sure the camera is available. If it is not (iPod touch or Simulator) I show the photo library instead.
-(void) showCamera
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else
{
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
imagePicker.delegate = self;
[viewController presentViewController:imagePicker animated:YES completion:nil];
}
//Here we intercept any time the webview tries to load a document. When the user hits our "showcamera: url" we go to work.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:
(UIWebViewNavigationType)navigationType
{
if ([request.URL.scheme isEqualToString:#"myApp"])
{
if ([request.URL.host isEqualToString:#"myFunction"])
{
[self showCamera];
}
return NO;
}
return YES;
}
//After the imagepicker has done it's thing, we pass the data back to the webview to be displayed.
//If we wanted to be fancy here, we could have done this via Javascript so we could dynamically insert an image without reloading the page.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[viewController dismissViewControllerAnimated:YES completion:nil];
UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation (image, 0.5);
NSURL *tmp = [NSURL URLWithString:#"ignore"];
[_viewWeb loadData:imageData MIMEType:#"image/jpeg" textEncodingName:#"UTF-8" baseURL:tmp];
}
#end
I have removed some code that was irrelevant
I have managed to fix the issue and it goes way back to bug that was found in iOS 8 that still hasn't been fixed. Its to do with how the UIWebView is being presented.
Adding this code fixed it.
-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
{
if ( self.presentedViewController)
{
[super dismissViewControllerAnimated:flag completion:completion];
}
}
For any one else confused or struggling with this Note that you do not need to start messing around with UIImagePicker or UIWebView delegates. Your web view should take care of opening the camera library or camera. This was a real pain of an issue so hopefully this may help others in my position. you can also see THIS Question as this is where i got my answer from. Thanks Andrey for helping too
As an alternative you can try to use UIWebViewDelegate's method webView:shouldStartLoadWithRequest:navigationType: to catch custom events:
In your HTML:
Do something
<button onclick="window.location.href='myApp://myFunction'">Do some action</button>
And then:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL.scheme isEqualToString:#"myApp"]) {
if ([request.URL.host isEqualToString:#"myFunction"]) {
// do something
}
return NO;
}
return YES;
}

How to write HTML iframe in tvos app for Apple TV

I am wondering how I can essentially wrap a webpage in some sort of iframe into a tvos app for the Apple TV. I was able to use a UITextView to write out basic HTML to display in a tvos app - basic div's with basic styling - however, I cannot figure out how to write out an iframe.
The code below, which is written in Objective C using XCode will display "hello!!!!" inside the Apple TV simulator, but not the iframe.
Here is my code below. Any help? Thanks!
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)print:(id)sender{
}
- (void)viewDidLoad {
[super viewDidLoad];
CGRect textViewFrame = CGRectMake(20.0f, 20.0f, 280.0f, 124.0f);
UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame];
textView.returnKeyType = UIReturnKeyDone;
[self.view addSubview:textView];
NSString* staticHTMLContent = #"<div>hello!!!!</div> <iframe frameborder=""1"" width=""420"" height=""345"" src=""//www.youtube.com/embed/C8kSrkz8Hz8""></iframe>";
NSAttributedString* myHTMLString = [[NSAttributedString alloc] initWithData:[staticHTMLContent dataUsingEncoding:NSUTF8StringEncoding] options:#{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType} documentAttributes:nil error:nil];
[textView setAttributedText:myHTMLString];
}
#end
A UITextView won't load an iframe. You need UIWebView to do that but that API isn't available in TvOS.
The reason the HTML shows up in you example is because you can render HTML/CSS in a UITextView as you're doing, but it isn't actually processed as if it was in a UIWebView, it's simply used for styling the content as an alternative to attributed text.