Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.m
- // ons.kg
- //
- // Created by Umar_Energizer on 11.09.16.
- // Copyright © 2016 ons.kg. All rights reserved.
- //
- @import FirebaseInstanceID;
- @import FirebaseMessaging;
- #import "ONSLoginViewController.h"
- #import "ONSAPIClient.h"
- #import "ONSUser.h"
- #import <SDWebImage/UIImageView+WebCache.h>
- //#import "KeychainItemWrapper.h"
- #import "ONSLoginViewController.h"
- @interface ONSLoginViewController ()
- {
- NSMutableArray *tbViewControllersFull;
- BOOL isExited;
- NSString* switchIsOn;
- NSString* topicID;
- }
- @property (assign, nonatomic, getter=isKeyboardVisible) BOOL keyboardVisible;
- @property (nonatomic, strong) IBOutlet UIButton *loginButton;
- @property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
- @property (strong, nonatomic) IBOutlet UISwitch *switchButton;
- @property (nonatomic, strong) IBOutlet UITextField *emailTextField;
- @property (nonatomic, strong) IBOutlet UITextField *passwordTextField;
- @property(nonatomic, strong) NSMutableData* receivedData;
- - (IBAction)hideKeyboard:(id)sender;
- @property (nonatomic, strong) ONSAPIClient* apiClient;
- @property (nonatomic, strong) NSString* login;
- @property (nonatomic, strong) NSString* password;
- // Личный кабинет
- @property (strong, nonatomic) IBOutlet UIView *selfCabinet;
- @property (strong, nonatomic) IBOutlet UILabel *familya;
- @property (strong, nonatomic) IBOutlet UILabel *name;
- @property (strong, nonatomic) IBOutlet UILabel *otchestvo;
- @property (strong, nonatomic) IBOutlet UIImageView *avatar;
- @property (strong, nonatomic) IBOutlet UILabel *userInfo;
- @property (strong, nonatomic) IBOutlet UILabel *os;
- @property (strong, nonatomic) IBOutlet UILabel *mail;
- @property (strong, nonatomic) IBOutlet UIButton *exitButtonOutlet;
- @end
- @implementation ONSLoginViewController
- @synthesize loginScrollView;
- @synthesize scrollView;
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.apiClient = [ONSAPIClient new];
- self.receivedData = [NSMutableData new];
- self.loginButton.layer.cornerRadius = 5.f;
- self.exitButtonOutlet.layer.cornerRadius = 5.f;
- UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dissmissKeyboard)];
- [self.view addGestureRecognizer:tap];
- }
- - (void)viewWillAppear:(BOOL)animated
- {
- [super viewWillAppear:animated];
- if ([ONSLoginViewController getToken])
- {
- self.navigationItem.title = @"Персональные данные";
- self.selfCabinet.hidden = NO;
- // [[[[self.tabBarController tabBar]items]objectAtIndex:1]setEnabled:TRUE];
- // [[[[self.tabBarController tabBar]items]objectAtIndex:2]setEnabled:TRUE];
- [self loadSelfCabinet];
- if([self.switchButton isOn]){
- switchIsOn = @"YES";
- [[NSUserDefaults standardUserDefaults] setObject:switchIsOn forKey:@"switchIsOn"];
- }
- else{
- switchIsOn = @"NO";
- [[NSUserDefaults standardUserDefaults] setObject:switchIsOn forKey:@"switchIsOn"];
- }
- [self setSwitch];
- }
- else
- {
- self.selfCabinet.hidden = YES;
- self.navigationItem.title = @"Вход пользователя";
- [[[[self.tabBarController tabBar]items]objectAtIndex:1]setEnabled:FALSE];
- [[[[self.tabBarController tabBar]items]objectAtIndex:2]setEnabled:FALSE];
- }
- self.keyboardVisible = NO;
- }
- - (void)postSendingMethodLogin
- {
- NSMutableData *data = [[NSMutableData alloc] init];
- self.receivedData = data;
- _login = self.emailTextField.text;
- _password = self.passwordTextField.text;
- if (_login && _password) {
- NSString * param = [NSString stringWithFormat:@"action=auth.php&login=%@&password=%@", _login, _password];
- NSData *postData = [param dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
- NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
- NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
- [request setURL:[NSURL URLWithString:@"http://ons.kg/json/auth.php"]];
- [request setHTTPMethod:@"POST"];
- [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
- [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
- [request setHTTPBody:postData];
- NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
- //start the connection
- [connection start];
- if (connection)
- {
- NSLog(@"Connected! URA!!!");
- }
- else
- NSLog(@"ERROR!!!");
- }
- else
- {
- UIAlertView *errorAlert = [[UIAlertView alloc]
- initWithTitle:@"Ошибка"
- message:@"Пожалуйста, заполните все поля и повторите попытку!"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [errorAlert show];
- }
- }
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- {
- [_receivedData setLength:0];
- NSHTTPURLResponse *resp = (NSHTTPURLResponse *) response;
- NSLog(@"got response with status @push %ld",(long)[resp statusCode]);
- }
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
- [_receivedData appendData:data];
- NSLog(@"recieved data @push %@", _receivedData);
- }
- - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- {
- UIAlertView *errorAlert = [[UIAlertView alloc]
- initWithTitle:@"Ошибка"
- message:@"Пожалуйста, проверьте соединение с Интернетом."
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- NSLog(@"Error is %@", error);
- [errorAlert show];
- }
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
- NSData *responseTextData = [[NSData alloc] init];
- responseTextData = _receivedData;
- NSDictionary *dicObject=[NSJSONSerialization
- JSONObjectWithData:responseTextData
- options:NSJSONReadingMutableLeaves
- error:nil];
- NSLog(@"didfinishLoading%@",dicObject);
- if ([[dicObject objectForKey:@"success"] isEqualToString:@"true"])
- {
- NSString* auth_token = [dicObject objectForKey:@"auth_token"];
- [self saveToken:auth_token];
- [self loadDataUsers];
- }
- else
- {
- UIAlertView *Alert = [[UIAlertView alloc]
- initWithTitle:@"Ошибка"
- message:@"Вы неправильно ввели логин или пароль!"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [Alert show];
- }
- }
- - (void)saveToken:(NSString*)token
- {
- [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
- [[NSUserDefaults standardUserDefaults] synchronize];
- }
- + (NSString *)getToken
- {
- NSLog(@"TOKEN IS: %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]);
- return [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
- }
- - (void)delTokenWithUser
- {
- NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
- NSDictionary * dict = [defs dictionaryRepresentation];
- for (id key in dict)
- {
- if ([key isEqualToString:@"token"]
- || [key isEqualToString:@"user_name"]
- || [key isEqualToString:@"user_last_name"]
- || [key isEqualToString:@"user_first_name"]
- || [key isEqualToString:@"user_email"]
- || [key isEqualToString:@"user_OS"]
- || [key isEqualToString:@"os_id"]
- || [key isEqualToString:@"user_info"]
- || [key isEqualToString:@"user_avatar"]
- || [key isEqualToString:@"user_id"])
- {
- [defs removeObjectForKey:key];
- }
- }
- [defs synchronize];
- }
- - (void) loadDataUsers
- {
- [self.apiClient browseUsersWithCompletion:^(NSArray<ONSUser*> *users)
- {
- dispatch_async(dispatch_get_main_queue(), ^
- {
- for (int i = 0; i < users.count; i++)
- {
- if ([_login isEqualToString:[users objectAtIndex:i].userEmail])
- {
- self.user = [ONSUser new];
- self.user = [users objectAtIndex:i];
- }
- }
- [self getUser];
- });
- }
- error:^(NSError *error)
- {
- NSLog(@"Error is: %@", error);
- }];
- }
- -(void) getUser
- {
- if (self.user)
- {
- isExited = NO;
- [UIView transitionWithView:_selfCabinet
- duration:0.4
- options:UIViewAnimationOptionTransitionFlipFromBottom
- animations:^{
- _selfCabinet.hidden = NO;
- }
- completion:NULL];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userName forKey:@"user_name"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userLName forKey:@"user_last_name"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userFName forKey:@"user_first_name"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userEmail forKey:@"user_email"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userOs forKey:@"user_OS"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.os_id forKey:@"os_id"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userId forKey:@"user_id"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userPhoto forKey:@"user_avatar"];
- [[NSUserDefaults standardUserDefaults] setObject:self.user.userProfessiya forKey:@"user_info"];
- [[NSUserDefaults standardUserDefaults] synchronize];
- topicID = [[NSUserDefaults standardUserDefaults] objectForKey:@"os_id"];
- [self loadSelfCabinet];
- self.navigationItem.title = @"Персональные данные";
- }
- }
- - (IBAction)LoginButton:(id)sender
- {
- [self hideKeyboard:sender];
- [self postSendingMethodLogin];
- }
- //- (BOOL)textFieldShouldReturn:(UITextField *)textField
- //{
- // [textField resignFirstResponder];
- // return YES;
- //}
- - (IBAction)hideKeyboard:(id)sender
- {
- [self dissmissKeyboard];
- }
- - (BOOL)prefersStatusBarHidden
- {
- return NO;
- }
- - (void) loadSelfCabinet
- {
- self.familya.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_first_name"]; //self.user.userFName;
- self.name.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_name"];
- self.otchestvo.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_last_name"];
- self.userInfo.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_info"];
- self.os.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_OS"];
- self.mail.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_email"];
- NSURL* imageURL =[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_avatar"]];
- [self.avatar sd_setImageWithURL:imageURL];
- [[[[self.tabBarController tabBar]items]objectAtIndex:1]setEnabled:TRUE];
- [[[[self.tabBarController tabBar]items]objectAtIndex:2]setEnabled:TRUE];
- NSString *token = [[FIRInstanceID instanceID] token];
- NSLog(@"InstanceID token: %@", token);
- NSString* topic = @"/topics";
- NSString* topicFullPath = [topic stringByAppendingPathComponent:topicID];
- [[FIRMessaging messaging] subscribeToTopic:topicFullPath];
- NSLog(@"Subscribed to news topic");
- }
- - (IBAction)exitButton:(UIButton *)sender {
- NSString* topic = @"/topics";
- NSString* topicFullPath = [topic stringByAppendingPathComponent:topicID];
- [[FIRMessaging messaging] unsubscribeFromTopic:topicFullPath];
- self.user = nil;
- isExited = YES;
- [UIView transitionWithView:_selfCabinet
- duration:0.5
- options:UIViewAnimationOptionTransitionFlipFromTop
- animations:^{
- _selfCabinet.hidden = YES;
- }
- completion:NULL];
- self.navigationItem.title = @"Вход пользователя";
- [self delTokenWithUser];
- self.familya.text = @"";
- self.name.text = @"";
- self.otchestvo.text = @"";
- self.userInfo.text = @"";
- self.os.text = @"";
- self.mail.text = @"";
- self.avatar.image = nil;
- self.passwordTextField.text = @"";
- [[[[self.tabBarController tabBar]items]objectAtIndex:1]setEnabled:FALSE];
- [[[[self.tabBarController tabBar]items]objectAtIndex:2]setEnabled:FALSE];
- }
- - (void) viewWillDisappear:(BOOL)animated{
- [super viewWillDisappear:animated];
- }
- -(BOOL)textFieldShouldReturn:(UITextField *)textField {
- if (textField == _emailTextField) {
- [textField resignFirstResponder];
- [_passwordTextField becomeFirstResponder];
- }
- else if (textField == _passwordTextField)
- {
- [_passwordTextField resignFirstResponder];
- [_loginButton becomeFirstResponder];
- [self postSendingMethodLogin];
- }
- return YES;
- }
- -(void)textFieldDidBeginEditing:(UITextField*)textField
- {
- CGPoint scrollPoint = CGPointMake(0, 50);
- [loginScrollView setContentOffset:scrollPoint animated:YES];
- }
- -(void)textFieldDidEndingEditing;
- {
- [loginScrollView setContentOffset:CGPointMake(0, -60) animated:YES];
- }
- -(void)dissmissKeyboard
- {
- [_emailTextField resignFirstResponder];
- [_passwordTextField resignFirstResponder];
- [self textFieldDidEndingEditing];
- }
- - (void) setSwitch
- {
- NSString* switchIsOnOff;
- switchIsOnOff = @"YES"; //[[NSUserDefaults standardUserDefaults] objectForKey:@"switchIsOn"];
- if([switchIsOnOff isEqualToString:@"YES"])
- {
- // [START subscribe_topic];
- // [END subscribe_topics
- // if ([[UIApplication sharedApplication]respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
- // {
- // // For iOS 8 and above
- // [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
- //
- // [[UIApplication sharedApplication] registerForRemoteNotifications];
- // }
- // else
- // {
- // // For iOS < 8
- // [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
- // (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
- // }
- }
- // if off
- else if([switchIsOnOff isEqualToString:@"NO"])
- {
- [[FIRMessaging messaging] unsubscribeFromTopic:topicID];
- //[[UIApplication sharedApplication] unregisterForRemoteNotifications];
- }
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement