how to access all index set from JSON data using NSDictionary - ios

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

Related

ERROR: _block_literal_generic or _block_invoke

I'm having an issue finding the source of this crash in my iOS app which has a core data model using iPhone app i am not able to login URl. I am using same code on iOS 7 its working but now I am trying to work on iOS 8.2.Have issue for _block_literal_generic
Block point is below As well check screen shot for block Error:---
[[NetwokManager sharedInstance] loginRequestEmail:userEmail andPassword:userPassword WithResponse:^(id responseObject, NSError *error) { if (!error) {
}
Using code is below:
-(void)sendLoginRequest
{
NSString *userEmail = [[NSUserDefaults standardUserDefaults] objectForKey:#"emailKey"];
NSString *userPassword = [[NSUserDefaults standardUserDefaults] objectForKey:#"passwordKey"];
NSLog(#"Email %#", userEmail);
NSLog(#"Password %#", userPassword);
NSString *mobileNo = [SCUserProfile currentUser].callerid;
NSLog(#"CallerID %#", mobileNo);
[[NetwokManager sharedInstance] loginRequestEmail:userEmail andPassword:userPassword WithResponse:^(id responseObject, NSError *error) {
if (!error) {
NSLog(#"responseString = %#", responseObject);
if (responseObject == nil)
{
NSLog(#"No data from server");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"No data downloaded from server!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
}
NSDictionary *resposneDict = (NSDictionary*)responseObject;
NSString *success = [resposneDict valueForKey:#"success"];
if ([success isEqual:#"Authentication Failed"])
{
[self showAlertViewWithMessage:#"Authentication Failed"];
// [self sendLogoutRequest];
[[C2CallAppDelegate appDelegate] logoutUser];
}
else if ([success intValue] == 1)
{
amobilePayUserID = [resposneDict valueForKey:#"user_id"];
[[NSUserDefaults standardUserDefaults] setValue:amobilePayUserID forKey:#"AMobilePay_User_ID"];
NSLog(#"User Id is:= %#",amobilePayUserID);
}
else if ([success intValue] == 0)
{
//[self sendRegistrationRequest];
// [self sendLogoutRequest];
// [[C2CallAppDelegate appDelegate] logoutUser];
}
else
{
[self showAlertViewWithMessage:#"Unable to login AmobilePay"];
}
} else {
[self showAlertViewWithMessage:[error localizedDescription]];
}
}];
}
Crash in unknown region 2015-04-30 09:56:18.390 AmobipayMerchant[337:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MOC2CallEvent costs]: unrecognized selector sent to instance 0x16ef2dd0'
Somewhere in the code, you called costs to an instance of MOC2CallEvent. MOC2CallEvent has no method or property costs, so of course it will crash.

Navigation in iOS using Objective-C

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

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

ios - Network / Internet Connection

After hours of searching on google I still cant find a single topic about this one:
1. I need to put error handling functions if the user does not have internet connection.
2. the user have internet connection but cant connect to the server .
And where can I put these? I tried one topic but it don't show the alert view message.
Here is my code:
- (IBAction)getDataPressed
{
if([myRequest_ isExecuting])
{
return;
}
if(myRequest_ != nil)
{
[myRequest_ release];
}
myRequest_ = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:URL_PATH]];
myRequest_.delegate = self;
[myRequest_ startAsynchronous];
}
#pragma ASI Delegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Request finished successfully");
NSLog(#"%#",[request responseString]);
NSDictionary *responseDictionary = [[request responseString]JSONValue];
NSDictionary *arrayElement = [responseDictionary objectForKey:#"user"];
NSString *ID = [arrayElement valueForKeyPath:#"id"];
NSLog(#"id: %#",ID);
NSString *usr = [arrayElement valueForKeyPath:#"usr"];
NSLog(#"usr: %#",usr);
NSString *gd = [arrayElement valueForKeyPath:#"gd"];
NSLog(#"gd: %#",gd);
NSString *ag = [arrayElement valueForKeyPath:#"ag"];
NSLog(#"ag: %#",ag);
NSString *st = [arrayElement valueForKeyPath:#"st"];
NSLog(#"st: %#",st);
NSString *lf = [arrayElement valueForKeyPath:#"lf"];
NSLog(#"lf: %#",lf);
NSString *da = [arrayElement valueForKeyPath:#"da"];
NSLog(#"da: %d",da);
for(NSString *value in [arrayElement allValues]){
NSLog(#"Found Value %#",value);
label.text = [value stringByAppendingFormat:#",%#,%#,%#,%#,%#,%#,",ID,usr,gd,ag,st,lf];
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(#"Error %#", [request error]);
if([request error])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Destination Unreachable" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void) dealloc
{
[super dealloc];
}
Thanks to those who will help ^_^
I think you could try the Reachbility application to help you out checking if you have internet or not. As for the server itself, you can use the NSUrlConnection Delegate methods to check if there was a problem with your request (by seeing the kind of HTTP code that comes)

Resources