how to find username and key in twitter in ios5.0 iphone - 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];
}

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.

How can i get access token from Twitter?

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

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

Facebook SDK + iPhone SDK + SSO

I know that this question has been asked, but I have been reading through threads all day and have applied all of the fixes I could find and am still having an issue.
I am trying to implement Facebook SDK's new SSO feature to allow my app to authenticate with Facebook's app instead of a webView. When my app switches to Facebook's app, it says loading for a few seconds and switches back but the token is still null. I have a feeling it has to do with the URL scheme for my app but I have followed many tutorials and am fairly confident that my current plist values are correct:
Here is the code I have implemented in my appDelegate and viewController files:
appDelegate.h
Facebook *facebook;
appDelegate.m
// Pre 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [facebook handleOpenURL:url];
}
// For 4.2+ support
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [facebook handleOpenURL:url];
}
SecondViewController.m
-(IBAction) fbButton {
//FACEBOOK INTEGRATION
appDelegate.facebook = [[Facebook alloc] initWithAppId:#"222087841143437" andDelegate:appDelegate];
// Check and retrieve authorization information
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
appDelegate.facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
appDelegate.facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![appDelegate.facebook isSessionValid]) {
appDelegate.facebook.sessionDelegate = self;
[appDelegate.facebook authorize:permissions];
NSLog(#"Token: %#", [defaults objectForKey:#"FBAccessTokenKey"]);
} else {
NSLog(#"Already logged in!");
}
[appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
NSString *nameID = [[NSString alloc] initWithFormat:#"%# (%#)", [result objectForKey:#"name"], [result objectForKey:#"id"]];
NSMutableArray *userData = [[NSMutableArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
[result objectForKey:#"id"], #"id",
nameID, #"name",
[result objectForKey:#"picture"], #"details",
nil], nil];
[userData release];
[nameID release];
NSLog(#"DATA RECEIVED: %#", result);
}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"request:didReceiveResponse:");
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"%#", [error localizedDescription]);
NSLog(#"Err details: %#", [error description]);
};
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[[appDelegate facebook] accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[[appDelegate facebook] expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
NSLog(#"Facebook Logged in!");
[appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self];
}
I know that I call [appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self] twice, but I don't think that's the problem.
Here is a snippet from the console when I press the login button:
2011-10-18 15:37:33.287 Track[2235:707] Token: (null)
2011-10-18 15:37:36.578 Track[2235:707] request:didReceiveResponse:
2011-10-18 15:37:36.584 Track[2235:707] The operation couldn’t be completed. (facebookErrDomain error 10000.)
2011-10-18 15:37:36.586 Track[2235:707] Err details: Error Domain=facebookErrDomain Code=10000 "The operation couldn’t be completed. (facebookErrDomain error 10000.)" UserInfo=0x1ce480 {error=<CFBasicHash 0x1c9560 [0x3e368630]>{type = mutable dict, count = 2,
entries =>
2 : <CFString 0x19a830 [0x3e368630]>{contents = "type"} = <CFString 0x11d230 [0x3e368630]>{contents = "OAuthException"}
3 : <CFString 0x1f5b60 [0x3e368630]>{contents = "message"} = <CFString 0x1f8a70 [0x3e368630]>{contents = "An active access token must be used to query information about the current user."}
I appreciate the help and I really hope I didn't miss a discussion on here that solves this problem. Here are a few (of the many) that I have read through and had no success in finding a solution
How to implement Single Sign On (SSO) using facebook ios sdk for iphone
Facebook SSO and request iOS SDK
Facebook API for iPhone Error: An active access token must be used
Make sure that your Facebook application (the actual application that you created on Facebook) is not in sandbox mode and if it is make sure that the user your Facebook application (the iPhone Facebook client) is currently logged in with is a developer for that application.