// // User.m // Juick // // Created by Vitaly on 01.02.14. // Copyright (c) 2014 com.juick. All rights reserved. // #import "User.h" #import "APIClient.h" @implementation User + (User *) fromJSON:(NSDictionary *)jsonData { User *user = [User new]; user.uid = jsonData[@"uid"]; user.uname = jsonData[@"uname"]; user.avatar = jsonData[@"avatar"]; return user; } +(BOOL) isAuthenticated { NSString *password = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.password"]; return password != nil; } +(void) throwUnableToLogin:(UIViewController *)view { UIAlertController *alert = [UIAlertController new]; [alert setTitle:@"Error"]; [alert setMessage:@"Unable to login, check username/password, or network connectivity"]; [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]]; UIPopoverPresentationController *popover = [alert popoverPresentationController]; if (popover) { popover.sourceView = view.view; popover.sourceRect = CGRectMake(CGRectGetMidX(view.view.bounds), CGRectGetMidY(view.view.bounds), 0, 0); popover.permittedArrowDirections = UIPopoverArrowDirectionDown; } [view presentViewController:alert animated:YES completion:nil]; } +(void) checkIsValid:(void (^)(BOOL))callback { AFHTTPSessionManager *manager = [APIClient sharedClient].manager; NSString *username = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.username"]; NSString *password = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.password"]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password]; [manager POST:@"post" parameters:nil progress:nil success:nil failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode; if (statusCode == 400) { callback(YES); } else { [manager.requestSerializer clearAuthorizationHeader]; callback(NO); } }];} +(void) get:(NSString *) name callback:(void(^)(User *))callback { AFHTTPSessionManager *manager = [APIClient sharedClient].manager; NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:name, @"uname", nil]; [manager GET:@"users" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { callback([User fromJSON:[(NSArray *)responseObject firstObject]]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { callback(nil); }]; } @end