currently iam using AepubReader for reading epub files,But i want to implement day and night mode in that?Do you know how can i implement that modes?
Currently iam using following code but the problems are
1.Night mode is only effecting a particular chapter.
2.Day mode changes font the color to black.
NSUserDefaults *userDefaults2 = [NSUserDefaults standardUserDefaults];
[userDefaults2 setBool:NO forKey:#"cc"];
[userDefaults2 synchronize];
[webView setOpaque:NO];
[webView setBackgroundColor:[UIColor blackColor]];
// for(int i=0;i<10;i++)
// {
NSString *jsString = [[NSString alloc] initWithFormat:#"document.getElementsByTagName('html')[0].style.webkitTextFillColor= 'white'"];
[webView stringByEvaluatingJavaScriptFromString:jsString];
// }
This code works for me
-(IBAction)night:(id)sender{
NSUserDefaults *userDefaults2 = [NSUserDefaults standardUserDefaults];
[userDefaults2 setBool:NO forKey:#"btnM1"];
[userDefaults2 synchronize];
[_webview setOpaque:NO];
[_webview setBackgroundColor:[UIColor blackColor]];
NSString *jsString = [[NSString alloc] initWithFormat:#"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
[_webview stringByEvaluatingJavaScriptFromString:jsString];}
-(IBAction)day:(id)sender{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:YES forKey:#"btnM1"];
[userDefaults synchronize];
[_webview setOpaque:NO];
[_webview setBackgroundColor:[UIColor whiteColor]];
NSString *jsString2 = [[NSString alloc] initWithFormat:#"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
[_webview stringByEvaluatingJavaScriptFromString:jsString2];}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSUserDefaults *menuUserDefaults = [NSUserDefaults standardUserDefaults];
if([menuUserDefaults boolForKey:#"btnM1"]){
[_webview setOpaque:NO];
[_webview setBackgroundColor:[UIColor whiteColor]];
NSString *jsString2 = [[NSString alloc] initWithFormat:#"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
[_webview stringByEvaluatingJavaScriptFromString:jsString2];
}
else{
[_webview setOpaque:NO];
[_webview setBackgroundColor:[UIColor blackColor]];
NSString *jsString = [[NSString alloc] initWithFormat:#"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
[_webview stringByEvaluatingJavaScriptFromString:jsString];
}}
You can use this code also for day & night mode. This code may be
work for as your need.
This will properly work for UIWebView.
The code is:
BOOL isNightMode;
- (IBAction)nightModeBtn_click:(id)sender {
isNightMode = YES;
[self.webView reload];
}
- (IBAction)dayModeBtn_click:(id)sender {
isNightMode = NO;
[self.webView reload];
}
- (void)webViewDidFinishLoad:(UIWebView *)_webView{
if(isNightMode == YES){
[self.webView setOpaque:NO];
NSString *setJavaScript = [[NSString alloc] initWithFormat:#" document.getElementsByTagName('body')[0].style.webkitFilter='grayscale(100%%)';document.getElementsByTagName('div')[0].style.webkitFilter='grayscale(100%%)'; DOMReady();"];
[self.webView stringByEvaluatingJavaScriptFromString:setJavaScript];
}
}
Related
I want to load a gif image with webView,And it works well.But when i find leaks with instruments,there is a memory leak. Who can tell me why,Here is the code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"icon_coinMoney_image" ofType:#"gif"];
UIWebView *gifWebView = ({
UIWebView *webView = [UIWebView new]; //Leaks Here
[self addSubview:webView];
[webView setBackgroundColor:[UIColor clearColor]];
webView.userInteractionEnabled = NO;
[webView setScalesPageToFit:YES];
webView.opaque = NO;
NSURL *url = [NSURL URLWithString:path];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
[webView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(backImageView.mas_left).offset(-MARGIN);
make.centerY.mas_equalTo(backImageView.mas_centerY).offset(1.f);
make.size.mas_equalTo(CGSizeMake(ZLL_AUTOSIZING_WIDTH(30.f), ZLL_AUTOSIZING_HEIGTH(30.f)));
}];
[webView.layer setMasksToBounds:YES];
[webView.layer setCornerRadius:ZLL_AUTOSIZING_WIDTH(15.f)];
webView;
});
I'm updating a webview app to the latest iOS SDK to support iOS 12.0. I used to call the session and login info through cookies and NSURLConnection so if user is logged in return username in sidemenu. After the update of the SDK and PODS I'm always getting the user as logged-out even though he's logged in and value of Loggedin = null.
My ViewController Code
- (void)viewDidLoad {
[super viewDidLoad];
preferences = [[NSUserDefaults alloc] init];
NSLog(#"perf %#", preferences)
isLoggedin = [preferences objectForKey:#"islogedin"];
NSLog(#"isLoggedin View Controller --- %#", isLoggedin)
}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
[self loadCookies];
// webView.hidden=NO;
// [SVProgressHUD dismiss];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
[self saveCookies];
// [SVProgressHUD dismissWithDelay:0.5 completion:^{
// webView.hidden=NO;;
//
// }];
}
-(void)saveCookies{
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: cookiesData forKey: #"cookies"];
[defaults synchronize];
}
- (void)loadCookies
{
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: #"cookies"]];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookies)
{
[cookieStorage setCookie: cookie];
}
}
-(void)getUserName
{
NSString *userName = #"";
NSString *string = [webview stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
NSData *tutorialsHtmlData = [string dataUsingEncoding:NSUTF8StringEncoding];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
NSString *tutorialsXpathQueryString = #"//span[#id='app_customer_name']";
NSArray *nodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
for (TFHppleElement *element in nodes) {
userName = [element valueForKey:#"text"];
[[NSUserDefaults standardUserDefaults] setObject:userName forKey:#"userName"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"username==%#", userName);
}
[[NSNotificationCenter defaultCenter]postNotificationName:#"name" object:userName];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self loadCookies];
}
-(void)doFurtherProcessingWithResult{
//NSLog(#"do furtherprocessing with result");
arrNavigation = [[NSMutableArray alloc] init];
NSError *error = nil;
NSData *objectData = [dataFromApi dataUsingEncoding:NSUTF8StringEncoding];
id collection = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error];
// id mainCollection = collection;
if(error){
NSLog(#"JSON data received is not in correct form");
}
NSArray *categories = [collection objectForKey:#"categories"];
for(NSObject *category in categories){
NSArray *children = [category valueForKey:#"children"];
//NSLog(#"child====%#", children);
NSString *htname = [category valueForKey:#"name"];
NSAttributedString * attrtitle = [[NSAttributedString alloc] initWithData:[htname dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSString *title = attrtitle.string;
NSString *link = [category valueForKey:#"path"];
NSString *icon = [category valueForKey:#"icon"];
NSString *image = [category valueForKey:#"image"];
NSMutableArray *sub = [[NSMutableArray alloc] init];
for (NSObject *child in children){
NSString *titlestr = [child valueForKey:#"name"];
NSAttributedString * attrsubtitle = [[NSAttributedString alloc] initWithData:[titlestr dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSString *title = attrsubtitle.string;
//NSLog(#"title--------------------");
NSString *link = [child valueForKey:#"path"];
NSDictionary *subdic = [NSDictionary dictionaryWithObjects:#[title, link] forKeys:#[#"title",#"link"]];
[sub addObject:subdic];
}
NSDictionary *dic = [NSDictionary dictionaryWithObjects:#[title,link,icon,image,sub] forKeys:#[#"title",#"link",#"icon",#"image",#"sub"]];
// NSLog(#"dic===has sub=%#", dic);
[arrNavigation addObject:dic];
}
//NSLog(#"viewcontroller-----%lu", (unsigned long)arrNavigation.count);
[[NSUserDefaults standardUserDefaults] setObject:arrNavigation forKey:#"sideMenu"];
[[NSUserDefaults standardUserDefaults] synchronize];
//NSLog(#"categories------%#", categories);
[[NSNotificationCenter defaultCenter]postNotificationName:#"reloadMenu" object:nil];
}
In my SideMenuVC I'm checking if the preference shows as logged in call the username else stay logged out.
#implementation SideMenuVC
- (void)viewDidLoad {
[super viewDidLoad];
preferences = [[NSUserDefaults alloc] init];
islogedin = [preferences objectForKey:#"islogedin"];
userName = #"";
if([preferences objectForKey:#"userName"]){
userName = [preferences objectForKey:#"userName"];
}
[self reloadMenu];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadMenu) name:#"reloadMenu" object:nil];
if([islogedin isEqualToString:#"true"]){
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(setName:) name:#"name" object:nil];
NSLog(#"User Loggedin")
} else {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(setLogout:) name:#"name" object:nil];
NSLog(#"User Loggedout")
}
}
-(void)setName:(NSNotification *)notification{
NSLog(#"logged in & received--------");
NSString *name = [notification object];
NSLog(#"the name is %#", name)
NSString *msg = [NSString stringWithFormat:#"Welcome %#", name];
[signinBtn setTitle:msg forState:UIControlStateNormal];
logoutBtn.hidden = NO;
islogedin = #"true";
}
-(void)setLogout:(NSNotification *)notification{
NSLog(#"loggedout--------");
//NSString *name = [notification object];
NSString *msg = [NSString stringWithFormat:#"Hello, Sign In"];
[signinBtn setTitle:msg forState:UIControlStateNormal];
logoutBtn.hidden = YES;
islogedin = #"false";
}
-(void)reloadMenu{
arrNavigation = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"sideMenu"]];
openSection = arrNavigation.count;
[leftPanel reloadData];
}
-(void)clearCookies{
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: #"cookies"]];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookies)
{
[cookieStorage deleteCookie: cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
When checking islogedin = [preferences objectForKey:#"islogedin"]; the return is null always while it should be TRUE or FALSE and always calling -(void)setLogout:
What did I do wrong and how can I resolve this issue?
I did not see anywhere you save your "islogedin" value to preferences.
Maybe in your SideMenuVC add some codes to save them like this
-(void)setName:(NSNotification *)notification{
...
islogedin = #"true"; //code
[preferences setObject:islogedin forKey:#"islogedin"];}
-(void)setLogout:(NSNotification *)notification{
...
islogedin = #"false"; // your code
[preferences setObject:islogedin forKey:#"islogedin"];}
BTW, in both files, one variable in first vc is "isLoggedin" while in the second class is "islogedin". See the difference. It may be overlooked.
My UIWebView doesn't seem to be loading:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSLog(#"%#", urlAddress);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:urlAddress]];
webView.delegate = self;
[webView loadRequest:requestObj];
}
It is in a UIViewController (connected through IB) and urlAddress returns google.com
Can you check if the URL being fetched is valid?
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSLog(#"%#", urlAddress);
NSURL *u = [NSURL URLWithString:urlAddress];
if(u){
NSURLRequest *requestObj = [NSURLRequest requestWithURL:u];
webView.delegate = self;
[webView loadRequest:requestObj];
}else{
[[[UIAlertView alloc] initWithTitle:#"" message:#"invalid url." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil] show];
}
google.com is not a valid url, it should be http://www.google.com. So maybe that is the issue here.
Try this code:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
webView.delegate = self;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSLog(#"%#", urlAddress);
[self openURLFromString:urlAddress];
}
- (void) openURLFromString:(NSString*) urlString
{
NSURL *url = [self validateAddress:urlString];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
}
- (NSURL*) validateAddress:(NSString*) address
{
NSURL* result = [NSURL URLWithString:address];
if (!result.scheme)
{
NSString* modifiedURLString = [NSString stringWithFormat:#"http://%#", address];
result = [NSURL URLWithString:modifiedURLString];
}
return result;
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSMutableURLRequest *)urlRequest navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
You're missing base URL part of the URL ( Click here to read more about this ), which is necessary.
So try this:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSString * theURL = [NSString stringWithFormat:#"http://%#", urlAddress]; // you can also use stringByAppendingString if you prefer
NSLog(#"%#", theURL);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]];
webView.delegate = self;
[webView loadRequest:requestObj];
}
HTH :)
I'm displaying list of PDF files in UIWebView along with UIButton. When I click the button I need to save my PDF file to iBooks and later user can read from iBooks.
Here is my code below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"mypdf" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
UIButton for download:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(download:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[webView addSubview:button];
-(void)download:(id)sender{
}
You have to use UIDocumentInteractionController for this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *pdfFilePath = [documentsDir stringByAppendingPathComponent:yourPdfFile.pdf];// your yourPdfFile file here
NSURL *url = [NSURL fileURLWithPath:pdfPath];
UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:url];
docController.delegate = self;
[docController retain];
// docController is released when dismissed (autorelease in the delegate method)
BOOL isValid = [docController presentOpenInMenuFromRect:yourReadPdfButton.frame inView:self.view animated:YES]; // Provide where u want to read pdf from yourReadPdfButton
if (!isValid) {
NSString * messageString = [NSString stringWithFormat:#"No PDF reader was found on your device. In order to consult the %#, please download a PDF reader (eg. iBooks).", yourPDFFileTitle];
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:messageString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
...
// UIDocumentInteractionController delegate method
- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller {
[controller autorelease];
}
Hope this will help you.
I'm following foursquare authen guideline but I still have a problem
this is my code
- (void)viewDidLoad
{
[super viewDidLoad];
self.webView.delegate = self;
NSString *clientID = #"XXX";
NSString *redirectURI = #"http://www.example.com";
NSString *authenticateURLString = [NSString stringWithFormat:#"https://foursquare.com/oauth2/authenticate?client_id=%#&response_type=token&redirect_uri=%#", clientID, redirectURI];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:authenticateURLString]];
[self.webView loadRequest:request];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL.scheme isEqualToString:#"itms-apps"]) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *URLString = [[self.webView.request URL] absoluteString];
NSLog(#"--> %#", URLString);
if ([URLString rangeOfString:#"access_token="].location != NSNotFound) {
NSString *accessToken = [[URLString componentsSeparatedByString:#"="] lastObject];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:#"access_token"];
[defaults synchronize];
[self dismissViewControllerAnimated:YES completion:nil];
}
}
but output from NSLog is only http://www.example.com. It has no access token return. Am i do anything wrong?
I'm open this link in Desktop Google Chrome and access token is successfully return. (www.example.com#access_token=XXX)
But I'm open this link in iPhone simulator's safari and it just return the url.
Thanks for help.
#nearonline
I have the same problem, and the reason is the URL in webViewDidFinishLoading will not contain the access token. But the URL in shouldStartLoadWithRequest will. Therefore you should modify the code into:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *URLString = [[request URL] absoluteString];
if ([URLString rangeOfString:#"access_token="].location != NSNotFound) {
NSString *accessToken = [[URLString componentsSeparatedByString:#"="] lastObject];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:#"access_token"];
[defaults synchronize];
[self dismissViewControllerAnimated:YES completion:nil];
return NO;
}
return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
}