//
// LoginViewController.h
#import <UIKit/UIKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKShareKit/FBSDKShareKit.h>
#import <GoogleSignIn/GIDSignIn.h>
#import <GoogleSignIn/GoogleSignIn.h>
#import <Chameleon.h>
@interface LoginViewController : UIViewController<GIDSignInDelegate, GIDSignInUIDelegate>
{
IBOutlet UITextField *txtEmail;
__weak IBOutlet UIImageView *splashImage;
IBOutlet UITextField *txtPassword;
IBOutlet UIButton *btnKeepMe;
IBOutlet UIButton *btnSignin;
IBOutlet UIScrollView *scContent;
IBOutlet GIDSignInButton *btnGoogleSignin;
}
@end
//
// LoginViewController.m
#import "LoginViewController.h"
#import "SignupViewController.h"
#import "ForgotPasswordViewController.h"
#import <Twitter/Twitter.h>
#import <TwitterCore/TwitterCore.h>
#import <TwitterKit/TWTRKit.h>
#import "CommonFunctions.h"
#import "HomeViewController.h"
#import <SVProgressHUD.h>
@import Firebase;
@import FirebaseAuth;
@interface LoginViewController ()
{
SignupViewController *signupViewController;
HomeViewController *homeViewController;
BOOL bImageLogin;
UIImage *imgUser;
NSString *strFirstName , *strLastName , *strSocialID ,*strPrfileImage;
NSString *strLoginBy;
}
@end
@implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"splash"]) {
splashImage.hidden = YES;
} else {
splashImage.hidden = NO;
[SVProgressHUD showWithStatus:Please_Wait_Msg];
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[self performSelector:@selector(hideSplash) withObject:nil afterDelay:3.0];
}
self.automaticallyAdjustsScrollViewInsets = NO;
scContent.scrollEnabled = NO;
strLoginBy = @"manual";
strFirstName = strLastName = strSocialID = @"";
[GIDSignIn sharedInstance].uiDelegate = self;
[GIDSignIn sharedInstance].delegate = self;
[btnSignin setBackgroundColor:[UIColor colorWithGradientStyle:UIGradientStyleLeftToRight withFrame:btnSignin.frame andColors:@[[UIColor colorWithHexString:@"#ee2b7a" withAlpha:1.0],[UIColor colorWithHexString:@"#f98bb7" withAlpha:1.0]]]];
}
- (void)viewDidAppear:(BOOL)animated{
[super viewWillAppear:YES];
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
[self setup];
}
-(void)hideSplash{
splashImage.hidden = YES;
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"splash"];
[SVProgressHUD dismiss];
}
-(void)viewWillAppear:(BOOL)animated{
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
#pragma mark Custom methods
-(void)setup
{
self.navigationController.navigationBar.hidden = YES;
btnSignin.layer.cornerRadius = btnSignin.frame.size.width/10;
btnKeepMe.layer.borderWidth = 1;
NSString *strUserName = [[CommonFunctions sharedInstance] getNSUserDefaultValue:@"userName"];
if (strUserName.length>0)
{
txtEmail.text = strUserName;
NSString *strPass = [[CommonFunctions sharedInstance] getNSUserDefaultValue:@"pass"];
txtPassword.text = strPass;
[btnKeepMe setSelected:YES];
UIImage *btnImage = [UIImage imageNamed:@"Checkbox-check.png"];
[btnKeepMe setImage:btnImage forState:UIControlStateNormal];
}
else
{
txtEmail.text = @"";
txtPassword.text = @"";
[btnKeepMe setSelected:NO];
UIImage *btnImage = [UIImage imageNamed:@"Checkbox.png"];
[btnKeepMe setImage:btnImage forState:UIControlStateNormal];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)keepMeClicked:(id)sender {
if (btnKeepMe.isSelected)
{
[btnKeepMe setSelected:NO];
UIImage *btnImage = [UIImage imageNamed:@"Checkbox.png"];
[btnKeepMe setImage:btnImage forState:UIControlStateNormal];
}
else
{
[btnKeepMe setSelected:YES];
UIImage *btnImage = [UIImage imageNamed:@"Checkbox-check.png"];
[btnKeepMe setImage:btnImage forState:UIControlStateNormal];
}
}
- (IBAction)btnSignInClicked:(id)sender {
/*
"bEmail":"sonawane.kuldeep@gmail.com",
"bPassword":"kuldeep@123",
"bDeviceType":"1",
"bDeviceUniqueId":"123456987258364",
"bLoginBy":"manual",
"bSocialId":"",
"bNotificationToken":"kjgdsfjasljkdfasdkjfasdk;j"
*/
[txtEmail resignFirstResponder];
[txtPassword resignFirstResponder];
NSString *strEmail = txtEmail.text;
NSString *strPassword = txtPassword.text;
if ([strLoginBy isEqualToString:@"manual"]) {
if (![self validateLoginDetails])
{
return;
}
}
if (btnKeepMe.isSelected)
{
//save user details
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"userName" value:strEmail];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"pass" value:strPassword];
}
else
{
//clear saved details
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"userName" value:@""];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"pass" value:@""];
}
NSString *strToken = [[CommonFunctions sharedInstance] getNSUserDefaultValue:@"deviceToken"];
NSString*strUDID = [[CommonFunctions sharedInstance] getDeviceID];
NSMutableDictionary *dicParameter = [[NSMutableDictionary alloc]init];
[dicParameter setValue:@"1" forKey:@"bDeviceType"];
[dicParameter setValue:strUDID forKey:@"bDeviceUniqueId"];
if (strToken.length ==0)
{ strToken = @"";
}
[dicParameter setValue:strToken forKey:@"bNotificationToken"];
[dicParameter setValue:strLoginBy forKey:@"bLoginBy"];
if (![strLoginBy isEqualToString:ManualLogin])
{
strEmail = @"";
strPassword = @"";
}
[dicParameter setValue:[strEmail lowercaseString] forKey:@"bEmail"];
[dicParameter setValue:strPassword forKey:@"bPassword"];
//social login fields
[dicParameter setValue:strSocialID forKey:@"bSocialId"];
[dicParameter setValue:strFirstName forKey:@"bFirstName"];
[dicParameter setValue:strLastName forKey:@"bLastName"];
[dicParameter setValue:@"" forKey:@"bPhoneNo"];
NSString *base64Image=@"";
NSString *strName=@"" ,*strType=@"";
if (bImageLogin)
{
NSData *imageData = UIImageJPEGRepresentation(imgUser, 1);
base64Image = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
strName = @"Img";
strType = @"application/jpg";
}
NSMutableDictionary *dicImage = [[NSMutableDictionary alloc]init];
[dicImage setObject:strName forKey:@"bName"];
[dicImage setObject:strType forKey:@"bType"];
[dicImage setObject:base64Image forKey:@"bFile"];
NSMutableArray *arrayImages = [[NSMutableArray alloc]init];
[arrayImages addObject:dicImage];
[dicParameter setObject:arrayImages forKey:@"bImage"];
WebHelper *web = [[WebHelper alloc]init];
web._webdelegate = self;
[web postData:login parameters:dicParameter];
}
- (IBAction)showForgotPassword:(id)sender {
ForgotPasswordViewController *forgot = [[ForgotPasswordViewController alloc]initWithNibName:@"ForgotPasswordViewController" bundle:nil];
[self.navigationController pushViewController:forgot animated:YES];
}
-(BOOL)validateLoginDetails
{
if (strSocialID.length >0) //if social login , no validtion required
{
return true;
}
if ([txtEmail.text length]== 0 || ![[CommonFunctions sharedInstance] validateEmail:txtEmail.text] )
{
[[CommonFunctions sharedInstance] showAlertView:@"Please enter valid email " view:self];
return false;
}
if ([txtPassword.text length]== 0 )
{
[[CommonFunctions sharedInstance] showAlertView:@"Please enter valid password " view:self];
return false;
}
return true;
}
- (IBAction)showSignUp:(id)sender {
SignupViewController *sinupController = [[SignupViewController alloc]initWithNibName:@"SignupViewController" bundle:nil];
[self.navigationController pushViewController:sinupController animated:YES];
// [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark Web delegate methods
-(void) didFinishLoadingData:(NSString *) strWebMethod data:(NSDictionary *)dicResponse
{
if ([[dicResponse valueForKey:@"status"] intValue] == 4) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Wrong Password" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
// [[CommonFunctions sharedInstance] resetUserDetails];
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
if([[dicResponse valueForKey:@"status"]intValue] == 10){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Email not found" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
if([[dicResponse valueForKey:@"status"]intValue] == 11){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Account is deleted" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
if([[dicResponse valueForKey:@"status"]intValue] == 12){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Blocked by Admin" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
[[CommonFunctions sharedInstance] resetUserDetails];
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
if([[dicResponse valueForKey:@"status"] intValue] == 23)
{
// // [self._webdelegate didFinishLoadingData:strAPIName data:dicResponse];
// [self._webdelegate didFinishLoadingData:strAPIName data:[NSDictionary dictionaryWithObjectsAndKeys:Email_verified_Msg, @"message" , nil]];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Email is not verified." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
else{
NSString *strUserid = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"userId"]];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"userId" value:strUserid];
NSString *strFirstName = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"firstName"]];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"firstName" value:strFirstName];
NSString *strLastname = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"lastName"]];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"lastName" value:strLastname];
NSString *strprofilePic;
//set token from header
NSDictionary *dicHeader = [dicResponse valueForKey:@"header"];
NSString *strToken = [dicHeader valueForKey:@"token"];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"token" value:strToken];
NSString *notificationCount = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"notificationCount"]];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"notificationCount" value:notificationCount];
NSDictionary *dicData = [dicResponse valueForKey:@"keyValue"];
S3BucketName = [dicData valueForKey:@"S3_BUCKET"];
S3_POOL_ID = [dicData valueForKey:@"S3_POOL_ID"];
S3_REGION = [dicData valueForKey:@"S3_REGION"];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"S3BucketName" value:S3BucketName] ;
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"S3_POOL_ID" value:S3_POOL_ID];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"S3_REGION" value:S3_REGION];
if ([strLoginBy isEqualToString:@"manual"])
{
strprofilePic = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"profilePic"]];
}
else //for social use local
{
strprofilePic = strPrfileImage;
}
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"profilePic" value:strprofilePic];
[[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"loginBy" value:strLoginBy];
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//navigate to home screen
UINavigationController *home = [[[CommonFunctions sharedInstance]getAppDelegateInstance] getHomeView];
[self.navigationController pushViewController:home animated:YES];
}
}
- (IBAction)fblogin:(id)sender {
FBSDKLoginManager *FBlogin = [[FBSDKLoginManager alloc] init];
FBlogin.loginBehavior = FBSDKLoginBehaviorWeb;
if ([UIApplication.sharedApplication canOpenURL:[NSURL URLWithString:@"fb://"]])
{
FBlogin.loginBehavior = FBSDKLoginBehaviorSystemAccount;
}
[FBlogin logInWithReadPermissions:@[@"public_profile", @"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
NSLog(@"Unexpected login error: %@", error);
NSString *alertMessage = error.userInfo[FBSDKErrorLocalizedDescriptionKey] ?: @"There was a problem logging in. Please try again later.";
[[CommonFunctions sharedInstance] showAlertView:alertMessage view:self];
}
else
{
if(result.token) // This means if There is current access token.
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
parameters:@{@"fields": @"name, email , first_name , last_name ,picture.type(large)"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id userinfo, NSError *error) {
if (!error) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
dispatch_async(dispatch_get_main_queue(), ^{
// you are authorised and can access user data from user info object
NSLog(@"fb user = %@", userinfo);
strFirstName = [userinfo valueForKey:@"first_name"];
strSocialID = [userinfo valueForKey:@"id"];
strLastName = [userinfo valueForKey:@"last_name"];
strPrfileImage = [[[userinfo valueForKey:@"picture"] valueForKey:@"data"] valueForKey:@"url"];
strLoginBy = @"facebook";
[self btnSignInClicked:nil];
});
});
}
else{
NSLog(@"%@", [error localizedDescription]);
[[CommonFunctions sharedInstance] showAlertView:error.description view:self];
}
}];
}
NSLog(@"Login Cancel");
}
}];
}
- (IBAction)googleSignin:(id)sender {
[GIDSignIn.sharedInstance signIn];
}
- (IBAction)twitterSignin:(id)sender {
[[Twitter sharedInstance] logInWithCompletion:^(TWTRSession *session, NSError *error)
// [[Twitter sharedInstance] logInWithViewController:self completion:^(TWTRSession *session, NSError *error)
{
if (session) {
NSLog(@"signed in as %@", [session userName]);
TWTRAPIClient *client = [[TWTRAPIClient alloc] initWithUserID:session.userID];
[client loadUserWithID:[session userID]
completion:^(TWTRUser *user,
NSError *error)
{
strSocialID = [session userID];
strFirstName = user.name;
strLastName = @"";
strPrfileImage =user.profileImageLargeURL;
strLoginBy = @"twitter";
[self btnSignInClicked:nil];
}];
} else {
NSLog(@"error: %@", [error localizedDescription]);
NSString *strError = @"User cancelled login flow.";
NSString *strActaulError = [error localizedDescription];
if(![strActaulError.lowercaseString isEqualToString:strError.lowercaseString]) //ignore cancel case
{
[[CommonFunctions sharedInstance] showAlertView:strActaulError view:self];
}
}
}];
}
- (IBAction)skipClicked:(id)sender {
UINavigationController *home = [[[CommonFunctions sharedInstance]getAppDelegateInstance] getHomeView];
[self.navigationController pushViewController:home animated:YES];
}
-(void) didFailed:(NSString *) strWebMethod data:(NSDictionary *)dicResponse statusCode:(NSInteger )strStatusCode
{
//fb log out
[[[FBSDKLoginManager alloc] init] logOut];
//google log out
[[GIDSignIn sharedInstance] signOut];
//twitter logout
NSString *signedInUserID = [TWTRAPIClient clientWithCurrentUser].userID;
if (signedInUserID) {
[[Twitter sharedInstance].sessionStore logOutUserID:signedInUserID];
}
if(strStatusCode == 23)
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Please enable location service for this app" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
if(strStatusCode == 10){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Email not found" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
exit(0);
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
if (strStatusCode == 12)
{
NSString *strMessage = Blocked_User_msg;
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:strMessage preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
[[CommonFunctions sharedInstance] resetUserDetails];
// exit(0);
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}else if (strStatusCode == SessionExpiredCode){
NSString *strMessage = Session_Expired_Msg;
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:strMessage preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
[[CommonFunctions sharedInstance] resetUserDetails];
// exit(0);
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
else
{
NSString *strMessage = [dicResponse valueForKey:@"message"];
if(strMessage.length==0)
{
strMessage = Request_Failed_Msg;
}
[[CommonFunctions sharedInstance] showAlertView:strMessage view:self];
}
}
#pragma mark google sign in deletegate methods
- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error {
if (!error)
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
dispatch_async(dispatch_get_main_queue(), ^{
// you are authorised and can access user data from user info object
strFirstName = user.profile.givenName;
strLastName = user.profile.familyName;
if (user.profile.hasImage)
{
strPrfileImage = [user.profile imageURLWithDimension:200].absoluteString;
}
GIDAuthentication *authentication = user.authentication;
FIRAuthCredential *credential =
[FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
accessToken:authentication.accessToken];
[[FIRAuth auth] signInWithCredential:credential
completion:^(FIRUser *user, NSError *error) {
if (error) {
// ...
return;
}
// User successfully signed in. Get user data from the FIRUser object
strSocialID = user.uid;
[self btnSignInClicked:nil];
NSLog(@"Google Response %@",strSocialID);
}];
strLoginBy = @"google";
// Perform any operations on signed in user here.
// strSocialID = user.userID; // For client-side use only!
//NSString *idToken = user.authentication.idToken; // Safe to send to the server
//NSString *fullName = user.profile.name;
// NSString *email = user.profile.email;
// [self btnSignInClicked:nil];
});
});
}
else
{
NSLog(@"error: %@", [error localizedDescription]);
NSString *strError = @"The user canceled the sign-in flow.";
NSString *strActaulError = [error localizedDescription];
if(![strActaulError.lowercaseString isEqualToString:strError.lowercaseString]) //ignore cancel case
{
[[CommonFunctions sharedInstance] showAlertView:strActaulError view:self];
}
}
}
- (void)signIn:(GIDSignIn *)signIn
didDisconnectWithUser:(GIDGoogleUser *)user
withError:(NSError *)error {
// Perform any operations when the user disconnects from app here.
// ...
// [[CommonFunctions sharedInstance] showAlertView:error.description view:self];
NSLog(@"error: %@", [error localizedDescription]);
NSString *strError = @"The user canceled the sign-in flow.";
NSString *strActaulError = [error localizedDescription];
if(![strActaulError.lowercaseString isEqualToString:strError.lowercaseString]) //ignore cancel case
{
[[CommonFunctions sharedInstance] showAlertView:strActaulError view:self];
}
}
@end
Define Keys in .Pch File
#define fbScheme @"fb175276849863XXX"
#define googleScheme @"465226450XXX-podrumdveesajjbaei1kgvmphc91bXXX.apps.googleusercontent.com"
#define googleScheme2 @"com.googleusercontent.apps.465226450XXX-podrumdveesajjbaei1kgvmphc91bXXX"
#define googleID @"465226450XXX-podrumdveesajjbaei1kgvmphc91bXXX"
#define twitterConsumerKey @"gCPhMbUjM5xm9zCLfuTCvdXXX"
#define twitterSecretKey @"s3gWraVSnDhKTyPpiHL5AeJqgcslZFbqm37RvfaIg8KW6k4XXX"
after that Select Project > Info > Url types
add url schemes for facebook like : fb175276849863XXX
add url schemes for twitter like : twitterkit-gCPhMbUjM5xm9zCLfuTCvdXXX
and also for Google
com.googleusercontent.apps.465226450XXX-podrumdveesajjbaei1kgvmphc91bXXX