ios - foursquare access token didn't come - ios

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 {
}

Related

UIWebview check if user is logged in and return True or False

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.

how to load a local html file if there is no internet connection

I have a number of uiwebview in my app that display html files hosted on a server. I would also like to have local copies of the html files that will display if there is no internet connection, but I don't understand how to do that. The .m files I have are similar to below.
Currently the uiwebview will display the remotely hosted page (in the example below "contact.html". Is anyone able to explain how I can load a local copy of the file if there is no internet available?
#import "ContactMeViewController.h"
#interface ContactMeViewController ()
#end
#implementation ContactMeViewController
- (void)viewDidLoad
{
NSString *urlAddress = #"http://www.domain.co.nz/apppages/contact.html";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webview loadRequest:requestObj];
webview.scalesPageToFit = YES;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
I have updated the .m file as follows, but get a blank screen with no internet connection instead of the local file loading:
#import "ContactMeViewController.h"
#interface ContactMeViewController (UIWebViewDelegate)
#end
#implementation ContactMeViewController
- (void)viewDidLoad
{
NSString *urlAddress = #"http://www.kuranimarsters.co.nz/apppages/contact.html";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webview loadRequest:requestObj];
webview.scalesPageToFit = YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (-1009 == kCFURLErrorNotConnectedToInternet) {
// if we can identify the error i.e, no internet connection
[self loadHtmlFile];
}
}
-(void)loadHtmlFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"contact.html"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSString* htmlString = [NSString stringWithContentsOfFile:content encoding:NSUTF8StringEncoding error:nil];
[webview loadHTMLString:htmlString baseURL:nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Apply delegates for UIWebView and in -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error load local html file.
By default, if internet is there -(void)webViewDidFinishLoad:(UIWebView *)webView, will get executed and you will see page as per URL.
you can store data of html file to document directory of app as.html file & load webview with this file on next time such as
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0],#"index.html"];
// Download and write to file
NSURL *url = [NSURL URLWithString:#"http://www.domain.co.nz/apppages/contact.html"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
// Load file in UIWebView
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
Use delegate methods of webView and implement it in ContactMeViewController.m
In didFailLoadWithError method you can identify error code using [error code]. You can use kCFURLErrorNotConnectedToInternet = -1009.
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if ([error code] == kCFURLErrorNotConnectedToInternet) {
// if we can identify the error i.e, no internet connection
[self loadHtmlFile];
}
}
-(void)loadHtmlFile
{
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"contact" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webview loadHTMLString:htmlString baseURL:nil];
}

UIWebView Not Loading View

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

Determine file extension on tap and push view controlelr

Basically I need to know how a webview knows what kind of file extension is being tapped, (png, zip, etc) and then push another view controller.
I have tried this before without the file extension code and it will push another view just fine.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if(navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *theRessourcesURL = [request URL];
DetailViewController *vc = [[DetailViewController alloc] init];
[vc downloadURL:theRessourcesURL userInfo:nil];
[self.navigationController pushViewController:vc animated:YES];
dlvc.delegate = self;
}
return YES;
}
Non-working code:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if(navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *theRessourcesURL = [request URL];
NSString *fileExtension = [theRessourcesURL pathExtension];
if ([fileExtension isEqualToString:#"png"]) {
MYViewController *vc = [[MYViewController alloc] init];
[dlvc downloadURL:theRessourcesURL userInfo:nil];
[self.navigationController pushViewController:vc animated:YES];
vc.delegate = self;
}
else{}
}
return YES;
}
Working for the most part.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if(navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *theRessourcesURL = [request URL];
NSString *fileExtension = [theRessourcesURL pathExtension];
NSLog(#"fileExtension is: %#", fileExtension);
if ([fileExtension isEqualToString:#"php"] || [fileExtension isEqualToString:#".png"] || [fileExtension isEqualToString:#".zip"] || [fileExtension isEqualToString:#".deb"] || [fileExtension isEqualToString:#".jpg"] || [fileExtension isEqualToString:#".mp3"]) {
NSError *error = nil; //error setting
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Downloads"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
HCDownloadViewController *dlvc = [[HCDownloadViewController alloc] init];
[dlvc downloadURL:theRessourcesURL userInfo:nil];
[self.navigationController pushViewController:dlvc animated:YES];
dlvc.delegate = self;
return NO;
}
else{}
}
return YES;
}
I also tried to use this as a starter base without success, as I don't use interface builder, so I don't know if IBActions can be used (if they can I dont know how to implement them properly). How to download files from UIWebView and open again
Any help would be appreciated.
Maybe you should put your if ([fileExtension isEqualToString:#"png"] || ...) inside if(navigationType == UIWebViewNavigationTypeLinkClicked){} and try again?

How can i add Day and Night Mode to AepubReader in ios

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

Resources