Retrieve screen_name's tweets after Twitter authentication - ios

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

Related

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

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

Is there a Firebase iOS Simple Login example for Twitter?

I'm having trouble coming up with a solution to the following from the Simple Login iOS quick start:
Since it is possible for a device to have more than one Twitter account attached, you will need to provide a block which can be used to determine which account to log in. Replace "[yourApp selectUserName:usernames]" below with your own code to choose from the list of usernames.
This is the code that is provided:
[authClient loginToTwitterAppWithId:#"YOUR_CONSUMER_KEY"
multipleAccountsHandler:^int(NSArray *usernames) {
// If you do not wish to authenticate with any of these usernames, return NSNotFound.
return [yourApp selectUserName:usernames];
} withCompletionBlock:^(NSError *error, FAUser *user) {
if (error != nil) {
// There was an error authenticating
} else {
// We have an authenticated Twitter user
}
}];
Would a UIActionSheet that allows the user to pick which account to use be best? How would that be done?
#import <Twitter/Twitter.h>
#import <Accounts/Accounts.h>
For login:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
// Request access from the user to use their Twitter accounts.
// [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
//NSLog(#"%#",error);
if(granted) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
//NSLog(#"%#",accountsArray);
twitterAccountsArray=[accountsArray mutableCopy];
if ([twitterAccountsArray count] > 0){
sheet = [[UIActionSheet alloc] initWithTitle:#"Choose an Account" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
for (ACAccount *acct in twitterAccountsArray) {
[sheet addButtonWithTitle:acct.username];
}
}
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
//NSLog(#"%#",error);
if (![error.localizedDescription isEqual:[NSNull null]] &&[error.localizedDescription isEqualToString:#"No access plugin was found that supports the account type com.apple.twitter"]) {
}
else
[Utility showAlertWithString:#"We could not find any Twitter account on the device"];
});
}
}];
It will open an action sheet which will show you the list of accounts your device has.
For posting :
There must be at least one valid twitter account added on your iPhone device.
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
NSString *initialText=#"Text to be posted";
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
tweetSheet.completionHandler = ^(SLComposeViewControllerResult result) {
switch(result) {
// This means the user cancelled without sending the Tweet
case SLComposeViewControllerResultCancelled:{
}
break;
case SLComposeViewControllerResultDone:{
}
break;
}
};
[tweetSheet setInitialText:initialText];
if (initialText) {
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
I've found a nice example of how to do this with Awesome Chat's code. It uses a UIActionSheet like I was attempting to.
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (IBAction)actionTwitter:(id)sender
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[ProgressHUD show:#"In progress..." Interaction:NO];
//---------------------------------------------------------------------------------------------------------------------------------------------
selected = 0;
//---------------------------------------------------------------------------------------------------------------------------------------------
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
//---------------------------------------------------------------------------------------------------------------------------------------------
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted)
{
accounts = [account accountsWithAccountType:accountType];
//-------------------------------------------------------------------------------------------------------------------------------------
if ([accounts count] == 0)
[self performSelectorOnMainThread:#selector(showError:) withObject:#"No Twitter account was found" waitUntilDone:NO];
//-------------------------------------------------------------------------------------------------------------------------------------
if ([accounts count] == 1) [self performSelectorOnMainThread:#selector(loginTwitter) withObject:nil waitUntilDone:NO];
if ([accounts count] >= 2) [self performSelectorOnMainThread:#selector(selectTwitter) withObject:nil waitUntilDone:NO];
}
else [self performSelectorOnMainThread:#selector(showError:) withObject:#"Access to Twitter account was not granted" waitUntilDone:NO];
}];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)selectTwitter
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:#"Choose Twitter account" delegate:self cancelButtonTitle:nil
destructiveButtonTitle:nil otherButtonTitles:nil];
//---------------------------------------------------------------------------------------------------------------------------------------------
for (NSInteger i=0; i<[accounts count]; i++)
{
ACAccount *account = [accounts objectAtIndex:i];
[action addButtonWithTitle:account.username];
}
//---------------------------------------------------------------------------------------------------------------------------------------------
[action addButtonWithTitle:#"Cancel"];
action.cancelButtonIndex = accounts.count;
[action showInView:self.view];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if (buttonIndex != actionSheet.cancelButtonIndex)
{
selected = buttonIndex;
[self loginTwitter];
}
else [ProgressHUD dismiss];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)loginTwitter
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
Firebase *ref = [[Firebase alloc] initWithUrl:FIREBASE];
FirebaseSimpleLogin *authClient = [[FirebaseSimpleLogin alloc] initWithRef:ref];
//---------------------------------------------------------------------------------------------------------------------------------------------
[authClient loginToTwitterAppWithId:TWITTER_KEY multipleAccountsHandler:^int(NSArray *usernames)
{
return (int) selected;
}
withCompletionBlock:^(NSError *error, FAUser *user)
{
if (error == nil)
{
if (user != nil) [delegate didFinishLogin:ParseUserData(user.thirdPartyUserData)];
[self dismissViewControllerAnimated:YES completion:^{ [ProgressHUD dismiss]; }];
}
else
{
NSString *message = [error.userInfo valueForKey:#"NSLocalizedDescription"];
[self performSelectorOnMainThread:#selector(showError:) withObject:message waitUntilDone:NO];
}
}];
}

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

What should i do, when user cant send message to twitter

I got app, which can send twits.
I do it in this way:
- (IBAction)twitDream:(id)sender
{
if ([TWTweetComposeViewController canSendTweet]) {
TWTweetComposeViewController *tweet =
[[TWTweetComposeViewController alloc] init];
if (dream.image != [UIImage imageNamed:#"blank-photo.png"])
[tweet addImage:dream.image];
NSString *twitMsg = [dreamField.text stringByAppendingString:#" send via Dreamer"];
[tweet setInitialText:twitMsg];
[self presentModalViewController:tweet animated:YES];
} else {
//can't tweet!
}
}
What should i do when [TWTweetComposeViewController canSendTweet] is equal to NO ? And when it is equal to NO ?
That is full solution code:
- (IBAction)twitDream:(id)sender
{
if ([TWTweetComposeViewController canSendTweet]) {
TWTweetComposeViewController *tweet =
[[TWTweetComposeViewController alloc] init];
if (dream.image != [UIImage imageNamed:#"blank-photo.png"]) {[tweet addImage:dream.image];}
NSString *twitMsg = [dreamField.text stringByAppendingString:#" #Dreamer"];
[tweet setInitialText:twitMsg];
[self presentModalViewController:tweet animated:YES];
} else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Sorry"
message:#"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}

Resources