How can i get access token from Twitter? - iphone

I have created titter login in my iphone application,here i want to send my access token and secret key to server for auto sharing functionality, i can't get my access token and sekret key ,please help me out thanks in advance.
This is my code:
ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterType
withCompletionHandler:^(BOOL granted, NSError *error){
if(!granted){
NSLog(#"%#",[error localizedDescription]);
}
NSLog(#"store %#",store);
}];
if([[store accounts] count] > 0)
{
NSLog(#"TWEET");
self.hasTwitterAccountAccess = YES;
}
else
{
NSLog(#"newlog");
self.hasTwitterAccountAccess = NO;
}
if(self.hasTwitterAccountAccess){
NSLog(#"login");
// If we have twitter access, refresh the table view
ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
}

You have to use Reverse OAuth: https://dev.twitter.com/docs/ios/using-reverse-auth

Related

Successfully login with Twitter using social framework but not able to fatch user profile in ios8

Following code I have implemented to login with Twitter in ios 8. With the help of this code I am able to successfully login after writing username and password in device's Setting's twitter app. But I am not able to fetch user's profile from Twitter. I am only able to fetch email address.(username for twitter). Following is my code.
In .h file I import frameworks like
#import <Accounts/Accounts.h>
#import <Accounts/AccountsDefines.h>
#import <Social/Social.h>
In .m file I write following code
- (IBAction)btnLoginWithTwiitterClicked:(id)sender {
//[AppCommon showProgressHUD:NSLocalizedString(#"ProgressHUD_LoadingData", #"'Loading Data','Laden van Gegevens','Daten werden geladen' -General message")];
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) // check Twitter is configured in Settings or not
{
self.accountStore = [[ACAccountStore alloc] init]; // you have to retain ACAccountStore
ACAccountType *twitterAcc = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[self.accountStore requestAccessToAccountsWithType:twitterAcc options:nil completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *accountsArray = [self.accountStore accountsWithAccountType:twitterAcc];
//[AppCommon hideProgressHUD];
NSDictionary *twitterAccount = [[self.accountStore accountsWithAccountType:twitterAcc] lastObject];
NSLog(#"Twitter UserName: %#", [twitterAccount valueForKey:#"username"]);
}
else
{
if (error == nil) {
//[AppCommon hideProgressHUD];
NSLog(#"User Has disabled your app from settings...");
}
else
{
//[AppCommon hideProgressHUD];
NSLog(#"Error in Login: %#", error);
}
}
}];
}
else
{
//[AppCommon hideProgressHUD];
NSLog(#"Not Configured in Settings......"); // show user an alert view that Twitter is not configured in settings.
}
}
Frinds further I have no idea how to fetch user's other detail.
Any help would be appriciable
Thanx in advance.
I am using same code
just try to NSLog or Po twitterAccount. You will see whole dictionary

iOS Facebook native login (without Facebook SDK)

I am trying to use native (iOS 6-7x) libraries to authorize a user with Facebook from my app. I would like to pass the auth token to my server when login is successful.
The code below works fine except when the user has not set up their Facebook account in the OS. I get the following error in this case:
Error Domain=com.apple.accounts Code=6 "The operation couldn’t be completed. (com.apple.accounts error 6.)
-(void) initFacebookLogin
{
LRAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.accountStore == nil)
appDelegate.accountStore = [[ACAccountStore alloc] init];
__block ACAccount *facebookAccount = nil;
ACAccountType *facebookAccountType = [appDelegate.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSArray * permissions = #[#"publish_stream", #"publish_actions", #"email"];
NSMutableDictionary *options = [[NSMutableDictionary alloc] initWithObjectsAndKeys:FACEBOOK_APP_ID, ACFacebookAppIdKey, permissions, ACFacebookPermissionsKey, ACFacebookAudienceOnlyMe, ACFacebookAudienceKey, nil];
[appDelegate.accountStore requestAccessToAccountsWithType:facebookAccountType
options: options
completion: ^(BOOL granted, NSError *error) {
if ( granted )
{
NSArray *accounts = [appDelegate.accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
ACAccountCredential* accountCredential = [facebookAccount credential];
NSString* token = [accountCredential oauthToken];
NSLog( #"token=%#", token );
}
else {
// WHAT DO I DO HERE???
// Error Domain=com.apple.accounts Code=6 "The operation couldn’t be completed. (com.apple.accounts error 6.)"
NSLog(#"%#", [error description]);
}
}];
}
Do I still need to use the Facebook SDK to ask the user to log in? Is there another iOS native library I could use to prompt the user to set up Facebook access in iOS?
OR, is there a better way to do streamlined Facebook auth (not asking the user to log in if they have already done so in the OS)?
You should take a look at Facebook docs here (there's a simple login example):
https://developers.facebook.com/docs/ios/ios-sdk-tutorial/authenticate/
In my opinion, I would use the Facebook SDK to perform the login, you can do something like this:
/* Constants */
#define K_FACEBOOK_REQUEST_CREDENTIALSURL #"me/?fields=id,location,name,username,bio,picture,gender,website,birthday,email"
#define K_FACEBOOK_PERMISSIONS #[#"user_about_me",#"user_birthday",#"email"]
/* Facebook Keys */
#define K_FACEBOOK_REQUEST_ID #"id"
#define K_FACEBOOK_REQUEST_USERNAME #"username"
#define K_FACEBOOK_REQUEST_LOCATION #"location"
#define K_FACEBOOK_REQUEST_FULLNAME #"name"
#define K_FACEBOOK_REQUEST_BIO #"bio"
#define K_FACEBOOK_REQUEST_WEBSITE #"website"
#define K_FACEBOOK_REQUEST_EMAIL #"email"
#define K_FACEBOOK_REQUEST_BIRTHDAY #"birthday"
#define K_FACEBOOK_REQUEST_GENDER #"gender"
- (void)initWithLoginFacebook
{
[PFFacebookUtils logInWithPermissions:K_FACEBOOK_PERMISSIONS block:^(PFUser *user, NSError *error) {
if (!user) {
if (!error)
NSLog("ERROR_CAUSE_AUTH_USERCANCELLED");
else
NSLog("ERROR_CAUSE_AUTH_FAILEDLOGIN");
} else if (user.isNew) {
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
if (error)
NSLog("ERROR_CAUSE_AUTH_FAILEDLOGIN");
else
[self requestLoginFacebook:result];
}];
} else
NSLog("User logged and not new!");
}];
}
- (void)requestLoginFacebook:(id)result
{
NSDictionary *userData = (NSDictionary *)result;
// Do something with the data... For example
NSString *facebookId = userData[K_FACEBOOK_REQUEST_ID];
NSString *name = userData[K_FACEBOOK_REQUEST_FULLNAME];
NSString *username = [userData[K_FACEBOOK_REQUEST_USERNAME] lowercaseString];
NSString *bio = userData[K_FACEBOOK_REQUEST_BIO];
NSString *website = userData[K_FACEBOOK_REQUEST_WEBSITE];
NSString *location = userData[K_FACEBOOK_REQUEST_LOCATION][#"name"];
NSString *gender = userData[K_FACEBOOK_REQUEST_GENDER];
NSString *birthday = userData[K_FACEBOOK_REQUEST_BIRTHDAY];
NSString *email = userData[K_FACEBOOK_REQUEST_EMAIL];
NSString *profileImage = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?width=180&height=180",userData[#"id"]];
}
You have to configure the Facebook SDK in the appDelegate and in the .plist file.
Your code only will work fine if the user has a Facebook account set in the device Settings.
I.

iOS User Login Session via Devise but Auth_token not kept

I am building an iphone app with a rails-backed server. I am using the devise gem. I am having trouble with user logins on the client-side (everything works on the web side, and even in the terminal with CURL).
On Xcode I can create a user and I can login. After logging in
(and recieving this in the log: "User logged in!")
I am then pushed to the indexViewController- and here I receive an error that the posts don't load. The reason is because on the post_controller.rb I have a
before_filter :authenticate_user!
preventing the posts from loading. The problem is, that the auth_token which was generated upon a successful login, is not being stored and passed along to the different views. So then, in the log I get:
'You need to sign in before continuing.'
As if the first part of what I just explained never happened..
In the indexViewController viewDidLoad method I have:
if (![[APIClient sharedClient] isAuthorized]) {
LoginViewController *loginViewController = [[LoginViewController alloc] init];
[self.navigationController pushViewController:loginViewController animated:YES];
}
isAuthorized is a BOOL in the APIClient that checks if userID>0
In the user model this is the code that creates a login session
+ (void)loginUser:(NSString *)signature
email:(NSString *)email
password:(NSString *)password
block:(void (^)(User *user))block
{
NSDictionary *parameters = #{ #"user": #{
// #"signature": signature,
#"email": email,
#"password": password
}
};
[[APIClient sharedClient] postPath:#"/users/sign_in" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
User *user = [[User alloc] initWithDictionary:responseObject];
if (block) {
block(user);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
if (block) {
block(nil);
}
}];
}
I am guessing it is here that I am missing some auth_token implementation? Since it is generated automatically by devise- I am not sure how to tell xcode to remember it. The auth_token is a string that has a column in the user table on the db. Should I add auth_token as param to the dictionary that holds the user's email and username? Or how do I get the token to persist?
Any ideas would be helpful.
Not being intimately familiar with AFNetworking this is a stab in the dark, but presumably you need to set the token for subsequent requests. Assuming APIClient is a wrapper you've added around AFHTTPClient, here's a quick idea of what that might look like after reviewing the code here - AFHTTPClient.
+ (void)loginUser:(NSString *)signature
email:(NSString *)email
password:(NSString *)password
block:(void (^)(User *user))block {
NSDictionary *parameters = #{ #"user": #{ #"email": email,
#"password": password } };
[[APIClient sharedClient] postPath:#"/users/sign_in"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
User *user = [[User alloc] initWithDictionary:responseObject];
// retrieve and save auth token
NSString *token = [responseObject objectForKey:#"authToken"];
[[APIClient sharedClient] setAuthorizationHeaderWithToken:token];
if (block) {
block(user);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
if (block) {
block(nil);
}
}];
}

Strange behaviour when trying to use Twitter ACAccount

I've been playing a bit with the new Social.Framework and in particular with SLRequest, both available on iOS 6 and upwards. Thing is, I got really surprised by a crash I've been getting when trying to post such request.
I've been getting the crash with both Facebook and Twitter accounts, so that's why I knew it wasn't related to any particular issue with one of them. It had to be related to the ACAccount object, which I'm getting in this way:
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"6.0")) {
//iOS 6
if (_twitterEnabled) {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
//Set up account
[accountStore requestAccessToAccountsWithType:accountTypeTwitter options:nil completion:^(BOOL granted, NSError *error) {
if (granted && !error) {
//Get account and get ready to post.
NSArray *arrayOfAccounts = [accountStore accountsWithAccountType:accountTypeTwitter];
if ([arrayOfAccounts count] > 0) {
_twitterAccount = [arrayOfAccounts lastObject];
}
}
}];
}
}
if (!_facebookEnabled) {
ACAccountType *accountTypeFacebook = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
NSArray *permissions = #[#"user_about_me",#"user_likes",#"email"];
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:kFacebookAppIDString, ACFacebookAppIdKey, permissions, ACFacebookPermissionsKey, ACFacebookAudienceFriends, ACFacebookAudienceKey, nil];
[accountStore requestAccessToAccountsWithType:accountTypeFacebook options:options completion:^(BOOL granted, NSError *error) {
if (granted && !error) {
[options setObject:#[#"publish_stream",#"publish_actions"] forKey:ACFacebookPermissionsKey];
[accountStore requestAccessToAccountsWithType:accountTypeFacebook options:options completion:^(BOOL granted, NSError *error) {
if (granted && !error) {
NSArray *arrayOfAccounts = [accountStore accountsWithAccountType:accountTypeFacebook];
if ([arrayOfAccounts count] > 0) {
_fbAccount = [arrayOfAccounts lastObject];
}
}
}];
}
}];
}
}
}
Both _twitterAccount and _fbAccount are ACAccount objects in which I store the relevant account when retrieved from the Account Store.
The problem came when later I tried to use such objects (I'll just post the twitter method for brevity's sake):
NSDictionary *twitterMsg = #{#"status" : message};
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"6.0")) {
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:kTwitterUpdateStatusURL parameters:twitterMsg];
[postRequest setAccount:_twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"Twitter HTTP response: %d", [urlResponse statusCode]);
}];
}
When calling setAccount: on postRequest I was getting an exception with the message: "Invalid account type for this request", which was obviously false. I also tried to debug the code and strangely the accountType on _twitterAccount was set to nil right before being sent to the ACAccount object. More strangely, if I put
NSLog(#"%#",_twitterAccount);
right under
_twitterAccount = [arrayOfAccounts lastObject]
on the first section of code, it works with no problem.
I've reviewed my code and I don't think I'm doing anything wrong so that I think it can be a bug on the framework? It looks like the ACAccountType is being released when it shouldn't, but I wanted to check if anyone of you could see anything wrong with my code that was provoking it and/or find an explanation for the issue, which I'm unable to solve by myself.
Thank you
UPDATE
It seems some other people have the same issue, I'm accepting one of the answers because it actually solves the issue, but I'll be looking forward to anyone that can find an explanation for the issue.
I was also getting "Invalid account type for this request" when using SLRequest on accounts retrieved via both of the following
ACAccountStore *account_store = [[ACAccountStore alloc] init];
ACAccountType *account_type_twitter = [account_store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// A.
NSArray *accounts = [account_store accountsWithAccountType:account_type_twitter];
// B.
NSString *account_id = #"id from doing account.identifier on one of the above";
ACAccount *account = [account_store accountWithIdentifier:account_id];
NSLog on the account had everything populated as expected but the type was set as null. Guessing this is a bug with Apple's SDK. Doing the following fixed the accounts for me so I could use them with SLRequest:
ACAccountType *account_type_twitter = [account_store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
account.accountType = account_type_twitter;
You have to retain ACAccountStore:
#property (nonatomic, strong) ACAccountStore *accountStore;
The ACAccount documentation never states specifically that you must retain ACAccountStore, but it does state that
"To create and retrieve accounts from the Accounts database, you must
create an ACAccountStore object. Each ACAccount object belongs to a
single ACAccountStore object."
When you call:
NSArray *accounts = [accountStore accountsWithAccountType:accountType]
Those accountStore objects in the array don't necessarily have all of their properties fetched from the database. Some properties (like accountType) are only retrieved from the Accounts database if needed. This caused the strange behavior that you saw when you logged the account and everything magically worked. When you logged the account, the ACAccountStore object was still in memory and the logging caused the retrieval of the AccountType property. At that point, the AccountType was retained with the ACAccount and everything was able to work later even after ACAccountStore was released.
Are you retaining the ACAccountStore you used to fetch the arraryOfAccounts?
I use this code without problem. (Twitter only)
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (!granted) {
NSLog(#"Access denied.");
}
else {
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
if (accounts.count > 0) {
twitterAccount = [accounts objectAtIndex:0];
}
}
}];
I think something about accountStore init issue?
Twitter's official reference is here.
Twitter: API requests with TWRequest

how to find username and key in twitter in ios5.0 iphone

Hi I am successfully integrated twitter in my iphone app with ios5.0.
My question is i have login with two accounts in twitter in ios 5.0 then for tweet from my app how i am know about which user tweeted or user id of Active account
use this methods to get the userinfo
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username
{
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
and also
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier
{
NSLog(#"User Info Received: %#", userInfo);
}
we will get the username here
in the TWTweetComposeViewController you can get a picker shown in image and you can select one of your account from it.
when you are tweeting directly , with the help of ACAccount you can get it by
+ (void)pritnUserName {
// Create an account store object.
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to use their Twitter accounts.
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if(granted) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
// For the sake of brevity, we'll assume there is only one Twitter account present.
// You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
if ([accountsArray count] > 0) {
// Grab the initial Twitter account to tweet from.
for (int i = 0 ; i < [accountsArray count] ;i++){
ACAccount *twitterAccount = [accountsArray objectAtIndex:i];
NSLog(#"username :%d is %#",i+1,twitterAccount.username);
}
}
}
}];
[accountStore release];
}