Navigation in iOS using Objective-C - ios

i have an ios app which uses a login page and after authenticating it enters into the inbox page.But after entering the inbox page it comes back automatically to the login page
Login.m
{
if ([username length] == 0 || [password length] == 0)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Oops!"
message:#"Make sure you enter a username and password!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Login_Info WHERE username='%#'",username]; // Execute the query.
NSLog(#" query = %#", query );
// Get the results.
if (self.arrLogin_Info != nil) {
self.arrLogin_Info = nil;
}
self.arrLogin_Info = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
[def setObject:[self.arrLogin_Info objectAtIndex:0] forKey:#"idKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:1] forKey:#"usernameKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:2] forKey:#"passwordKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:3] forKey:#"emailKey"];
NSLog(#" query output = %#", self.arrLogin_Info);
NSString *val = [self.arrLogin_Info objectAtIndex:2];
// NSLog(#" val = %#",val);
if ([val isEqualToString:password] )
{
// NSLog(#" Inside if before entering app");
[self.navigationController popToRootViewControllerAnimated:YES];
}
else
{
//NSLog(#" Inside else before entering app");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!"
message:#"Please ensure you have entered the correct password!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}
}
#end
Inbox.m
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
id u = [def objectForKey:#"idkey"];
if(u)
{
NSString *query = [NSString stringWithFormat:#"Select *from Messages where recipient_ID=%#",u];
self.msg = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// [self.tableView reloadData];
}
else
{
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
// [self.tableView reloadData];
}
- (IBAction)logout:(id)sender {
//[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"showLogin" ])
{
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
}

Your Inbox view controller uses the presence of an object for the key 'idkey' in NSUserDefaults to determine whether the user is already logged in, or whether to show the login screen.
I presume that this line in login.m
[def setObject:[self.arrLogin_Info objectAtIndex:0] forKey:#"idKey"];
is supposed to be setting that key, but you don't show where you initialise def - so my guess is that this is nil and you aren't saving the data in NSUserDefaults.
Also, all of this -
if (self.arrLogin_Info != nil) {
self.arrLogin_Info = nil;
}
self.arrLogin_Info = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
can be simplified to this
self.arrLogin_Info = [self.dbManager loadDataFromDB:query];

Related

Login UIAlertView on multiple ViewControllers

I'm trying to make a log in system for the app I am developing for a class project. This log in button would display on the navigation bar of most views so I was thinking of a separate class to initialize in the various view controllers to create the UIAlertView and handle the app to server communication. The issue I'm having is changing the Log In text to Log Out after the username and password has been checked and saved. I have been able to show the UIAlertView and talk with the server but am stuck on changing the text. I initially put a method in the view controller to change the text, with no success, but within the user file would be preferable. It is my first time using a singleton so I'm not interely sure on the correctness. Am I going about this the wrong way, is there a better way? Thanks for any help.
HomeViewController.m
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.navigationController setNavigationBarHidden:NO animated:YES];
self.navigationController.navigationBar.topItem.title = #"Home";
UIBarButtonItem *login = [[UIBarButtonItem alloc] initWithTitle:#"Log In" style:UIBarButtonItemStylePlain target:self action:#selector(log)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = login;
}
-(void)log {
User* singleton = [User getInstance];
[singleton sign];
}
/*
-(void)logfinish {
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"Username"] && [[NSUserDefaults standardUserDefaults] stringForKey:#"Password"]) {
UIBarButtonItem *logout = [[UIBarButtonItem alloc] initWithTitle:#"Log Out" style:UIBarButtonItemStylePlain target:self action:nil];
self.navigationController.navigationBar.topItem.rightBarButtonItem = logout;
}
}*/
User.m
#implementation User
static User *singletonInstance;
+ (User*)getInstance{
if (singletonInstance == nil) {
singletonInstance = [[super alloc] init];
}
return singletonInstance;
}
-(void)sign {
if (![[NSUserDefaults standardUserDefaults] stringForKey:#"Username"] && ![[NSUserDefaults standardUserDefaults] stringForKey:#"Password"]) {
signAlert = [[UIAlertView alloc] initWithTitle:#"Log In" message:#"Please sign into your account" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Log In", nil];
signAlert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[signAlert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *person = [signAlert textFieldAtIndex:0].text;
NSString *pass = [signAlert textFieldAtIndex:1].text;
NSDictionary *params = # {#"User": person, #"Password" :pass};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:signIn parameters:params success:^(AFHTTPRequestOperation *operation, NSData* response) {
NSString *responsef = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSLog(#"%#", responsef);
[self check:responsef user:params];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
-(void)check:(NSString*) pass user:(NSDictionary*)nandp {
if ([pass isEqualToString:#"Success"]) {
[[NSUserDefaults standardUserDefaults] setValue:[nandp objectForKey:#"User"] forKey:#"Username"];
[[NSUserDefaults standardUserDefaults] setValue:[nandp objectForKey:#"Password"] forKey:#"Password"];
//NSLog(#"%# logged in", [[NSUserDefaults standardUserDefaults] stringForKey:#"Username"]);
//HomeViewController *view = [[HomeViewController alloc] init];
//[view logfinish];
}
else NSLog(#"Failure");
}
This is just one way of doing it.
Declare an instance variable like:
#implementation User {
UIViewController *viewController;
}
Pass the viewController you are calling from as a parameter to the method sign such as:
-(void)sign:(UIViewController *)viewControllerParam {
if (![[NSUserDefaults standardUserDefaults] stringForKey:#"Username"] && ![[NSUserDefaults standardUserDefaults] stringForKey:#"Password"]) {
signAlert = [[UIAlertView alloc] initWithTitle:#"Log In" message:#"Please sign into your account" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Log In", nil];
signAlert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
viewController = viewControllerParam; // assigning to ivar for future use
[signAlert show];
}
}
Save this param to your instance variable for future reference. Now you can use this variable for calling a method in your viewController which changes the right bar button item:
-(void)check:(NSString*) pass user:(NSDictionary*)nandp {
if ([pass isEqualToString:#"Success"]) {
[[NSUserDefaults standardUserDefaults] setValue:[nandp objectForKey:#"User"] forKey:#"Username"];
[[NSUserDefaults standardUserDefaults] setValue:[nandp objectForKey:#"Password"] forKey:#"Password"];
[viewController logfinish]; // call the respective method
}
else NSLog(#"Failure");
}
Hope this helps! :)

how to access all index set from JSON data using NSDictionary

I am trying to get my user name and password, which I am getting from my server. I already store in jsondata which is NSMutableArray. However I am getting only one data via -objectAtIndex:. I want to call my all data inside the dictionary. I know I have to use NSIndexSet but I don't know the proper way to use it. I'm using a for loop. I'm not able to access my value for key to match user credentials. Can anybody suggest anything? Here's my code:
NSDictionary *dict = [jsondata objectAtIndex:0];
if ([username.text isEqualToString:[dict valueForKey:#"username"]]&&[password.text isEqualToString:[dict valueForKey:#"password"]]) {
username.text=nil;
password.text=nil;
[self performSegueWithIdentifier:#"login" sender:nil];
}
else {
UIAlertView *error=[[UIAlertView alloc]initWithTitle:#"Oooops" message:#"Login Credentials did`t Match" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[error show];
}
NSString *tusername = nil;
NSString *tpassword = nil;
BOOL isLogin = NO;
//jsondata contains many dictionary, so iterate the loop and find the dictionary that
//contains username and password
for(id temp in jsondata)
{
//check whether the object is Dictionary or not
if([temp isKindOfClass:[NSDictionary class]])
{
NSDictionary *dict = temp;
if([[dict allKeys] containsObject:#"username"])
{
tusername = [dict valueForKey:#"username"];
}
else if([[dict allKeys] containsObject:#"password"])
{
tpassword = [dict valueForKey:#"password"];
}
//Check the condition here
if(tusername != nil && tpassword != nil)
{
if ([username.text isEqualToString:tusername] && [password.text isEqualToString:tpassword])
{
isLogin = YES;
username.text=nil;
password.text=nil;
[self performSegueWithIdentifier:#"login" sender:nil];
break;
}
}
}
}
if(!isLogin)
{
UIAlertView *error=[[UIAlertView alloc]initWithTitle:#"Oooops" message:#"Login Credentials did`t Match" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[error show];
}
You need to call a loop to access all the data on jsondata. Call as follows:
for (int i=0; i<[jsondata count]; i++)
{
NSDictionary *dict = [jsondata objectAtIndex:i];
if ([username.text isEqualToString:[NSString stringWithFormat: #"%#",[dict valueForKey:#"username"]]]&&[password.text isEqualToString:[NSString stringWithFormat: #"%#",[dict valueForKey:#"password"]]]) {
username.text=nil;
password.text=nil;
[self performSegueWithIdentifier:#"login" sender:nil];
}
else {
UIAlertView *error=[[UIAlertView alloc]initWithTitle:#"Alert Title" message:#"Your alert messege" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[error show];
}
}

Need suggestion to integrate gmail account in iOS developlment

I am new to iOS programming, and just want to do something fun.
I want to develop a mail client app for iPhone, it can add email accounts such as gmail and Yahoo and so on. I searched online for a while and also find some answers, before I dive into the details I just want someone who has similar experience give me some suggestions about which method is the best.
thanks
I have recently implemented gmail api to fetch gmail contacts and their email in my tableview. Gmail api is depricated, thats why you might have not got any proper documentation for that.
To implement gmail use libGDataTouchStaticLib.a library, with Gdata headers (search on google for that otherwise send me your email i will send you its zip).
The code to get gmail details are as follows
- (void)getGoogleContacts {
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
// request a whole buncha contacts; our service object is set to
// follow next links as well in case there are more than 2000
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket {
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService {
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
// update the username/password each time the service is requested
NSString *username = [txtUserName text];
NSString *password = [txtPasswrod text];
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
// contacts fetched callback
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[mutAryGoogleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
NSMutableDictionary *aDictContactDetails=[NSMutableDictionary dictionary];
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString* ContactEmail = [email address];
if (ContactEmail) {
[aDictContactDetails setObject:ContactEmail forKey:#"email"];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
if (ContactName) {
[aDictContactDetails setObject:ContactName forKey:#"friendName"];
}
[mutAryGoogleContacts addObject:aDictContactDetails];
}
}
//Push to next vc or do whatever you want
}
}

Retrieve screen_name's tweets after Twitter authentication

I want recent 20 statuses of screen_name after successful authentication.
I have done authentication successfully.
Here is my code here for retrieving tweets:
- (void)listResults
{
NSLog(#"list");
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:#"#uknationofblue" count:30 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];
NSLog(#"%#",dict);
NSArray *results = [dict objectForKey:#"statuses"];
NSLog(#"array text = %#",results);
for (NSDictionary *item in results)
{
NSLog(#"text == %#",[item valueForKey:#"text"]);
NSLog(#"name == %#",[[item objectForKey:#"user"]objectForKey:#"name"]);
NSLog(#"screen name == %#",[[item objectForKey:#"user"]objectForKey:#"screen_name"]);
NSLog(#"pic == %#",[[item objectForKey:#"user"]objectForKey:#"profile_image_url_https"]);
}
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
});
}
});
}

How to define username and password in row of picker [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a picker 5 row (0, 1, 2, ...5) and I want to define if I select row:0 and I click button
"Login" will show alertView to add Username and Password which Username and Password in row:0
must be A and A only when I click "Login" in alertView go to(modal) View:A but Username and
Password not A and A show alertView "Username or Password wrong"
and row:1 working same from row:0 but Username and Password must be B and B only and
go to(modal) View:B not View:A
Any suggestions?
- (void)viewDidLoad
{
[super viewDidLoad];
_Data = [[NSArray alloc] initWithObjects:#"Place1", #"Place2", #"Place3", #"Place4", #"Place5", #"Place6", nil];
}
- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [_Data count];
}
-(NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [_Data objectAtIndex:row];
}
- (IBAction)ShowID:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please Login" message:#"Enter Username and Password" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Login", nil];
[alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[alert show];
}
Try something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary* dict1 = [NSDictionary dictionaryWithObjectsAndKeys: #"Place1", #"place", #"TSViewController1", #"vcclass", #"User1", #"userName", #"qwerty", #"password", nil];
NSDictionary* dict2 = [NSDictionary dictionaryWithObjectsAndKeys: #"Place1", #"place", #"TSViewController1", #"vcclass", #"User2", #"userName", #"wwwrtt", #"password", nil];
_Data = [[NSArray alloc] initWithObjects: dict1, dict2, nil];
}
-(NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [[_Data objectAtIndex: row] objectForKey: #"place"];
}
- (IBAction)ShowID:(id)sender
{
NSInteger indexPicker = [_pickerView selectedRowInComponent: 0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Login"
message: [NSString stringWithFormat: #"Enter Username and Password for %#", [_Data objectAtIndex: indexPicker]]
delegate: self
cancelButtonTitle: #"Cancel"
otherButtonTitles: #"Login", nil];
[alert setAlertViewStyle: UIAlertViewStyleLoginAndPasswordInput];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Login"])
{
NSInteger indexPicker = [_pickerView selectedRowInComponent: 0];
NSString* username = [[_Data objectAtIndex: indexPicker] objectForKey: #"userName"];
NSString* password = [[_Data objectAtIndex: indexPicker] objectForKey: #"password"];
NSString* yourUsername = [alertView textFieldAtIndex:0].text;
NSString* yourpassword = [alertView textFieldAtIndex:1].text;
if ([username isEqualToString: yourUsername] && [yourpassword isEqualToString: password])
{
NSString* viewControllerClassName = [[_Data objectAtIndex: indexPicker] objectForKey: #"vcclass"];
Class classOfViewController = NSClassFromString(viewControllerClassName);
UIViewController* viewController = [[classOfViewController alloc] init];
[self presentModalViewController: viewController
animated: YES];
// or [self.navigationController pushViewController:viewController animated:YES];
}
}
}
In .h:
#interface ...
{
NSArray* _DataLogin;
NSArray* _Data;
UIPickerView* _pickerView;
}
Then you should create your custom view controllers. You can also use presentModalViewController instead of the pushViewController.

Resources