Retrieving twitter user data with iOS Social / Accounts frameworks - ios

Is there a way to get user data (first name, last name, and email) from Twitter using the iOS social/accounts frameworks? I'm able to do it with Facebook, but every SLRequest I make to Twitter returns an empty array.
Here's the code I've got right now. I've tried several URLS with varying parameters, but I haven't had any luck.
- (void)populateTwitterAccount {
NSURL *twitterURL = [NSURL URLWithString:#"https://api.twitbridge.com/1.1/users/show.json"];
SLRequest *twitterRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:twitterURL parameters:nil];
[twitterRequest setAccount:self.twitterAccount];
[twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *accountDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", accountDataString);
}];
}

yes we can.
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSString *message = _textView.text;
//hear before posting u can allow user to select the account
NSArray *arrayOfAccons = [account accountsWithAccountType:accountType];
for(ACAccount *acc in arrayOfAccons)
{
NSLog(#"%#",acc.username);
NSDictionary *properties = [acc dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"properties"]];
NSDictionary *details = [properties objectForKey:#"properties"];
NSLog(#"user name = %#",[details objectForKey:#"fullName"]);//full name
NSLog(#"user_id = %#",[details objectForKey:#"user_id"]);//user id
}
for email id,
we can also able to get user email id see the updated answer hear

Yes, you can get user information using ACAccountStore,
You have to retain ACAccountStore:
.h
#property (nonatomic, strong) ACAccountStore *account;
.m
NSUrl *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/users/show.json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:twittername,#"screen_name",nil];
account = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSArray *twitterAccounts = [account accountsWithAccountType:twitterAccountType];
// Runing on iOS 6
if (NSClassFromString(#"SLComposeViewController") && [SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
[account requestAccessToAccountsWithType:twitterAccountType options:NULL completion:^(BOOL granted, NSError *error)
{
if (granted)
{
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:params];
[request setAccount:[twitterAccounts lastObject]];
dispatch_async(dispatch_get_main_queue(), ^
{
[NSURLConnection sendAsynchronousRequest:request.preparedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^
{
if (data)
{
// [self loadData:data];
NSString* newStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
NSLog(#"data:%#",newStr);
}
});
}];
});
}
}];
}
else if (NSClassFromString(#"TWTweetComposeViewController") && [TWTweetComposeViewController canSendTweet]) // Runing on iOS 5
{
[account requestAccessToAccountsWithType:twitterAccountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted)
{
TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];
[request setAccount:[twitterAccounts lastObject]];
dispatch_async(dispatch_get_main_queue(), ^
{
[NSURLConnection sendAsynchronousRequest:request.signedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^
{
if (data)
{
NSString* newStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"data:%#",newStr); }
});
}];
});
}
}];
}
}

Related

How to get Email param of facebook using SLRequest in iOS Social Framework

I tried the below code for getting email of the person who logged in iOS Settings Facebook.
Please help me how to get email from SLRequest.
- (void) getMyDetails {
if (! _accountStore) {
_accountStore = [[ACAccountStore alloc] init];
}
if (! _facebookAccountType) {
_facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSDictionary *options = #{ ACFacebookAppIdKey: FB_APP_ID };
[_accountStore requestAccessToAccountsWithType: _facebookAccountType
options: options
completion: ^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [_accountStore accountsWithAccountType:_facebookAccountType];
_facebookAccount = [accounts lastObject];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:url
parameters:nil];
request.account = _facebookAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"id: %#", responseDictionary[#"id"]);
}];
}
}];
}
Here is the code tested on iOS 8 that returns email. The solution doesn't require Facebook SDK, although the system grants access to Facebook account only if a user logged in with Facebook in Settings app.
// Required includes
#import Accounts;
#import Social;
// Getting email
ACAccountStore *theStore = [ACAccountStore new];
ACAccountType *theFBAccountType = [theStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *theOptions = #{
ACFacebookAppIdKey : #"YOUR_APP_ID",
ACFacebookPermissionsKey : #[#"email"]
};
[theStore requestAccessToAccountsWithType:theFBAccountType options:theOptions completion:^(BOOL granted, NSError *error) {
if (granted) {
ACAccount *theFBAccount = [theStore accountsWithAccountType:theFBAccountType].lastObject;
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"https://graph.facebook.com/me"]
parameters:#{#"fields" : #[#"email"]}];
request.account = theFBAccount;
[request performRequestWithHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil && ((NSHTTPURLResponse *)response).statusCode == 200) {
NSError *deserializationError;
NSDictionary *userData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&deserializationError];
if (userData != nil && deserializationError == nil) {
NSString *email = userData[#"email"];
NSLog(#"%#", email);
}
}
}];
}
}];
You can get email id by below mentioned way.
Call Facebook graph API by the help of access token that you got from Account store
And yes, to get email id from Facebook, you need to provide "email" permission while requesting access token, without the permission you won't be able to get email parameter
Here is my code
NSString *FB_EncodedToken = [APP_CONSTANT.facebookToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *opearation = [AFHTTPRequestOperationManager manager];
opearation.requestSerializer = [AFHTTPRequestSerializer serializer];
opearation.responseSerializer = [AFJSONResponseSerializer serializer];
NSString *strUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me?"];
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:FB_EncodedToken,#"access_token", nil];
[opearation GET:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLogs(#"Description %#",responseObject);
//Lets pasre the JSON data fetched from facebook
[self parseUserDetail:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLogs(#"Error description %#",error.description);
self.completionHandler(error);
}];
Then parse the data
-(void)parseUserDetail:(NSDictionary *)dict
{
FBProfileBO *profile = [[FBProfileBO alloc] init];
profile.userFirstName = [dict objectForKey:#"first_name"];
profile.userLastName = [dict objectForKey:#"last_name"];
profile.userEmail = [dict objectForKey:#"email"];
profile.userName = [dict objectForKey:#"name"];
profile.userDOB = [dict objectForKey:#""];
profile.facebookId = [dict objectForKey:#"id"];
//Call back methods
self.completionHandler(profile);
profile = nil;
}

What is wrong with Twitter API on iOs 8?

I want to create an action in Objetive-C that makes an instant "follow" in a Twitter Acount, but when I launch my app it crashes. Could anyone tell me what is wrong?
It returns thread 1 exc_bad_access.
- (IBAction)Twitter:(id)sender {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil
completion:^(BOOL granted, NSError *error) {
if(granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 0) {
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"user" forKey:#"UserName"];
[tempDict setValue:#"true" forKey:#"follow"];
NSURL *URLTwitter = [NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.format"];
SLRequest *postRequest = [SLRequest requestForServiceType:#"Twitter" requestMethod:SLRequestMethodPOST URL:URLTwitter parameters:tempDict];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %li", [urlResponse statusCode]];
NSLog(#"%#", output);
}];
}
}
}];
}
Your twitter url is incorrect. It should be
https://api.twitter.com/1.1/friendships/create.json
Here is what was wrong...
1. Firstly, since the new Twitter API version 1.1 the correct URL is: https://api.twitter.com/1.1/friendships/create.json.
2. The 'for key' value for the user name must to be "screen_name", and it will be like the following fragment:
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"UserNameOnTwitter" forKey:#"screen_name"];
[tempDict setValue:#"true" forKey:#"follow"];
The value for 'requestForServiceType' must to be SLServiceTypeTwitter as the following:
SLRequest *postRequest = [SLRequest requestForServiceType: SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:URLTwitter parameters:tempDict];
So the whole block will be:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil
completion:^(BOOL granted, NSError *error) {
if(granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 0) {
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"UserNameOnTwitterWithoutAt" forKey:#"screen_name"];
[tempDict setValue:#"true" forKey:#"follow"];
NSURL *URLTwitter = [NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"];
SLRequest *postRequest = [SLRequest requestForServiceType: SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:URLTwitter parameters:tempDict];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %li", [urlResponse statusCode]];
NSLog(#"%#", output);
}];
}
}
}];
Thanks anyway everyone.

How to get user info who is getting sign in using twitter SLRequest?

I would like to get user profile information using SLRequest in twitter?
Currently I am coding like
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/users/show.json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:#"ali",#"screen_name",nil];
account = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSArray *twitterAccounts = [account accountsWithAccountType:twitterAccountType];
// Runing on iOS 6
if ([LoginViewController isTwitterAvailable])
{
NSLog(#"In the IFF...... ");
[account requestAccessToAccountsWithType:twitterAccountType options:NULL completion:^(BOOL granted, NSError *error)
{
NSLog(#"in body ");
if (granted)
{
NSLog(#"in granted ..");
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:params];
[request setAccount:[twitterAccounts lastObject]];
dispatch_async(dispatch_get_main_queue(), ^
{
[NSURLConnection sendAsynchronousRequest:request.preparedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^
{
if (data)
{
//NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
//NSLog(#"data:%#",string);
NSError* error;
NSDictionary* dicUser = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
It returns the whole of the info, not profile info,
How can I get profile info of user who is getting sign in ?
Thanks
Try folowing code giving from one of the live project, you can modify as per your existing structure. Let me know in case of any problem.
_accountStore = [[ACAccountStore alloc] init]; //Declare accountStore as property and initialize
ACAccountType *accountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[_accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error){
if (granted){
NSArray *accounts = [_accountStore accountsWithAccountType:accountType];
if (accounts.count > 0){
ACAccount *twitterAccount = [accounts lastObject];
NSDictionary *dict1 = [twitterAccount dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"properties"]];
NSDictionary *properties = dict1[#"properties"];
NSDictionary *returnDict = #{#"TwitterID":properties[#"user_id"],#"UserName":twitterAccount.username};
NSLog(#"Profile details->%#",properties);
}else{
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:kTwitterErrorMsg forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:#"Domain" code:error.code userInfo:details];
NSLog(#"Error occured->%#",error.localizedDescription);
}
} else {
NSMutableDictionary* details = [NSMutableDictionary dictionary];
if(error.code == ACErrorAccountNotFound){
[details setValue:kTwitterErrorMsg forKey:NSLocalizedDescriptionKey];
}else if(error.code == ACErrorPermissionDenied || error.code == ACErrorAccessDeniedByProtectionPolicy) {
[details setValue:kTwitterAccessDeniedMsg forKey:NSLocalizedDescriptionKey];
}else {
[details setValue:kTwitterErrorMsg forKey:NSLocalizedDescriptionKey];
}
error = [NSError errorWithDomain:#"Domain" code:error.code userInfo:details];
NSLog(#"Error occured->%#",error.localizedDescription);
}
}];
Few macros
#define kTwitterErrorMsg #"Please set your Twitter account in Settings."
#define kTwitterAccessDeniedMsg #"Twitter Access denied."

best way to implement twitter

1) I have found the Twitter rush sample code from this link Twitter with OAuth
for the integration.
I have added consumer key and secret key. But it never authorizes the app.
2) And if I use share kit it gives the error that there was a problem requesting access from twitter.
3) If I use social framework then it will give alert if user hasn't added his/her account in settings.
I need that user shouldn't go outside the app for twitter login.
Does anyone have any idea on what would be the best way to integrate with twitter?
Please help.
I Hope This will help you . . .
1.Add following classes to your project
GTMOAuthAuthentication.h/m
GTMOAuthSignIn.h/m
GTMHTTPFetcher.h/m
GTMOAuthViewControllerTouch.h/m
GTMOAuthViewTouch.xib
2 . Add following frameworks
Security.framework and SystemConfiguration.framework.
3 .set -ObjC build option for the application target's "Other Linker Flags".
4 . Then it's time for some coding .
import GTMOAuthAuthentication.h and GTMOAuthViewControllerTouch.h
- (void)signInWithTwitter
{
NSURL *requestURL = [NSURL URLWithString:#"https://api.twitter.com/oauth/request_token"];
NSURL *accessURL = [NSURL URLWithString:#"https://api.twitter.com/oauth/access_token"];
NSURL *authorizeURL = [NSURL URLWithString:#"https://api.twitter.com/oauth/authorize"];
NSString *scope = #"http://api.twitter.com/";
GTMOAuthAuthentication *auth = [self authForTwitter];
[auth setCallback:#"http://www.noop.com/OAuthCallback"];
GTMOAuthViewControllerTouch *viewController;
viewController = [[GTMOAuthViewControllerTouch alloc] initWithScope:scope
language:nil
requestTokenURL:requestURL
authorizeTokenURL:authorizeURL
accessTokenURL:accessURL
authentication:auth
appServiceName:#"AppName : Twitter"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[appDelegate.navigationController pushViewController:viewController animated:YES];
}
- (GTMOAuthAuthentication *)authForTwitter {
GTMOAuthAuthentication *auth = [[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
consumerKey:TWITTER_CONSUMER_KEY
privateKey:TWITTER_CONSUMER_SECRET];
[auth setServiceProvider:#"Twitter"];
return auth;
}
- (void)viewController:(GTMOAuthViewControllerTouch *)viewController finishedWithAuth:(GTMOAuthAuthentication *)auth error:(NSError *)error {
if(error)
{
//handle error
}
else
{
// do stuff as per your app.
}
}
NOte : if you get error message like "failed to validate oauth signature and token" then check you system time is correct or not .
If you want that user shouldn't go outside you can use ACAccountStore Account.Framework and Social.framework for iOS 6,
NSUrl *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/users/show.json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:twittername,#"screen_name",nil];
account = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSArray *twitterAccounts = [account accountsWithAccountType:twitterAccountType];
// Runing on iOS 6
if (NSClassFromString(#"SLComposeViewController") && [SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
[account requestAccessToAccountsWithType:twitterAccountType options:NULL completion:^(BOOL granted, NSError *error)
{
if (granted)
{
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:params];
[request setAccount:[twitterAccounts lastObject]];
dispatch_async(dispatch_get_main_queue(), ^
{
[NSURLConnection sendAsynchronousRequest:request.preparedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^
{
if (data)
{
// [self loadData:data];
NSString* newStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
NSLog(#"data:%#",newStr);
}
});
}];
});
}
}];
}
else if (NSClassFromString(#"TWTweetComposeViewController") && [TWTweetComposeViewController canSendTweet]) // Runing on iOS 5
{
[account requestAccessToAccountsWithType:twitterAccountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted)
{
TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];
[request setAccount:[twitterAccounts lastObject]];
dispatch_async(dispatch_get_main_queue(), ^
{
[NSURLConnection sendAsynchronousRequest:request.signedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^
{
if (data)
{
NSString* newStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"data:%#",newStr); }
});
}];
});
}
}];
}
}
You have to retain ACAccountStore: in .h
#property (nonatomic, strong) ACAccountStore *account;

How to make multiple posts to Twitter via iOS?

I am attempting to post to Twitter without user interaction (as this would force the user to hit 'Send' multiple times.).
The following is my code:
- (void) postToTwitterUsingTWRequest: (NSDictionary*) appDictionary {
NSString *trackName = [appDictionary objectForKey:#"trackName"];
NSString *trackId = [[appDictionary objectForKey:#"trackId"] description];
NSString *artworkUrl512 = [appDictionary objectForKey:#"artworkUrl512"];
NSMutableString *requestUrlString = [NSMutableString new];
[requestUrlString appendFormat:#"http://itunes.apple.com/%#",[[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]];
[requestUrlString appendFormat:#"/app/%#", trackName];
[requestUrlString appendFormat:#"/id%#?mt=8", trackId];
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES) {
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"] parameters:nil requestMethod:TWRequestMethodPOST];
//NSData *tempData = [NSData dataWithContentsOfURL:[NSURL URLWithString: #"http://eborkdev.com/wp-content/uploads/2012/05/logo.png"]];
NSData *tempData = [NSData dataWithContentsOfURL:[NSURL URLWithString: artworkUrl512]];
[postRequest addMultiPartData:tempData withName:#"media" type:#"image/png"];
tempData = [[NSString stringWithFormat:#"%# was recommended using Tell A Friend (http://link_to_tell_a_friend.com). \n %#", trackName, requestUrlString] dataUsingEncoding:NSUTF8StringEncoding];
[postRequest addMultiPartData:tempData withName:#"status" type:#"text/plain"];
[postRequest setAccount:twitterAccount];
isPostingToTwitter = true;
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
isPostingToTwitter = false;
NSLog(#"Twitter HTTP response: %i", [urlResponse statusCode]);
}];
}
else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"No Twitter accounts found. Please ensure that there are accounts present, and try again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
}];
}
I am looping through this in order to make the multiple calls like so:
for (NSDictionary* appDictionary in selectedApps) {
[self postToTwitterUsingTWRequest:appDictionary];
}
Sometimes it allows me to send one giving me the 200 statusCode. But when sending multiple, I get 403 and 200, or just 403.
How can I fix this?
You should read the following links before proceeding, the thing you are trying to do is called spamming..
https://dev.twitter.com/docs/error-codes-responses
https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following
TRY THIS
AT .H
#import <Twitter/Twitter.h>
#import <Accounts/Accounts.h>
- (void)sendTweet
{
Class tweeterClass = NSClassFromString(#"TWTweetComposeViewController");
if(tweeterClass != nil) { // check for Twitter integration
if ([TWTweetComposeViewController canSendTweet])
{
// Create account store, followed by a twitter account identifier
// At this point, twitter is the only account type available
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
// Sanity check
if ([arrayOfAccounts count] > 0)
{
// Keep it simple, use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
// Build a twitter request
TWRequest *postRequest = [[TWRequest alloc] initWithURL:
[NSURL URLWithString:#"http://api.twitter.com/1/statuses/update.json"]
parameters:[NSDictionary dictionaryWithObject:str_tweet
forKey:#"status"] requestMethod:TWRequestMethodPOST];
// Post the request
[postRequest setAccount:acct];
// Block handler to manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
// NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// NSLog(#"Twitter response: %#, HTTP response: %#", response, [urlResponse statusCode]);
}];
}
}
}];
}
else
{
NSLog(#"Unable to tweet!");
}
}
}

Resources