Here is my code for "follow on twitter" (iOS6+):
-(IBAction)twitterFollow
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if(granted) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
NSLog(#"twitter accounts: %#", accountsArray);
if ([accountsArray count] > 0) {
// Grab the initial Twitter account to tweet from.
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"myapp" forKey:#"screen_name"];
[tempDict setValue:#"true" forKey:#"follow"];
//requestForServiceType
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1/friendships/create.json"] parameters:tempDict];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i Error %d", [urlResponse statusCode],error.code];
NSLog(#"%#error %#", output,error.description);
NSString *twitterErrorMessage = [error localizedDescription];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kDefaultErrorText message:twitterErrorMessage delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert performSelectorOnMainThread:#selector(show)
withObject:nil
waitUntilDone:NO];
}];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kDefaultErrorText message:kTextMessageNoTwitter delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert performSelectorOnMainThread:#selector(show)
withObject:nil
waitUntilDone:NO];
}
}
}];
}
This is what I get:
HTTP response status: 410 Error 0error (null)
What am I doing wrong?
The screen name and account are valid:
twitter accounts: (
"type:com.apple.twitter\nidentifier: 2ABCDEC6-9D6B-1234-9AB7-847EB167B123\naccountDescription: #theuser\nusername: theuser\nobjectID: x-coredata://ABD5C87A-FB5D-464E-AF18-2C1123451123/Account/p13\nenabledDataclasses: {(\n)}\nenableAndSyncableDataclasses: {(\n)}\nproperties: {\n fullName = theuser;\n \"user_id\" = 147712345;\n}\nparentAccount: (null)\nowningBundleID:(null)"
)
Well, I got rid of the 410 error by using the 1.1 API:
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"] parameters:tempDict];
Now I get a 400 error:
HTTP response status: 400 Error 0error (null)
Which suggested invalid authentication, even though the code above looks exactly like the code I see on every tutorial/example I find. I guess I'll create another question...
Related
I want to send the messages and want to post on facebook and twitter in background is there any possible framework is there to do this.Can any one share the idea please.Thanks in advance .
To post on Twitter in background use this library https://github.com/nst/STTwitter
You will need to register your app on Twitter to receive consumer key and consumer secret. After you have it just use the code represented here Accessing Twitter Direct Messages using SLRequest iOS. This code uses system Twitter credentials, user have to set these credentials in iPhone / iPad settings.
Regarding to post on Facebook: I found no wrapper for iOS which can provide possibility to post in background. I use official Facebook iOS SDK is here https://github.com/facebook/facebook-ios-sdk. But post functionality works only with user's participation.
For facebook make sure you have the user permission or sdk setup properly. I would recommend to go through this tutorial for details.
http://m-farhan.com/2014/03/ios-facebook-sdk-tutorial/
- (void)requestPermissionAndPost {
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", #"publish_checkins",nil]
defaultAudience:FBSessionDefaultAudienceEveryone
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Now have the permission
[self postOpenGraphAction];
} else {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self presentAlertForError:error];
}
}
}];
}
- (void)postOpenGraphAction
{
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
};
UIImage *img = imageView.image;
NSString *message = #"Your Message";
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/photos" parameters:[NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation(img, 0.7),#"source",message,#"message",#"{'value':'EVERYONE'}",#"privacy", nil] HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
[self.requestConnection cancel];
self.requestConnection = newConnection;
[newConnection start];
}
// FBSample logic
// Report any results. Invoked once for each request we make.
- (void)requestCompleted:(FBRequestConnection *)connection
forFbID:fbID
result:(id)result
error:(NSError *)error
{
NSLog(#"request completed");
// not the completion we were looking for...
if (self.requestConnection &&
connection != self.requestConnection)
{
NSLog(#" not the completion we are looking for");
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error)
{
NSLog(#" error");
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// error contains details about why the request failed
[alert show];
}
else
{
NSLog(#" ok");
NSLog(#"%#",result);
/*[[[UIAlertView alloc] initWithTitle:#"Result"
message:[NSString stringWithFormat:#"Posted Open Graph action, id: %#",
[result objectForKey:#"id"]]
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];*/
[self doCheckIn];
};
}
fro Twitter its simple and easy
#import <Twitter/Twitter.h>
- (void)TWPostImage:(UIImage *)image withStatus:(NSString *)status
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
//ACAccountStore *accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *ac;
if(granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
int i=0;
for (ACAccount *account in accountsArray ) {
i++;
NSLog(#"Account name: %#", account.username);
ac=account;
}
if (i==0) {
[[[UIAlertView alloc] initWithTitle:#"Wait"
message:#"Please setup Twitter Account Settigns > Twitter > Sign In "
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
return ;
}
ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];;
//SLRequestHandler requestHandler;
SLRequestHandler requestHandler =
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (responseData) {
NSInteger statusCode = urlResponse.statusCode;
if (statusCode >= 200 && statusCode < 300) {
NSDictionary *postResponseData =
[NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:NULL];
NSLog(#"[SUCCESS!] Created Tweet with ID: %#", postResponseData[#"id_str"]);
ESAppDelegate* d =[[UIApplication sharedApplication] delegate];
NSString* link = [NSString stringWithFormat:#"Your Message",twitterAccStore,hashtagFromStore];
[d linkSelected:link PointerToSelf:self];
/*[[[UIAlertView alloc] initWithTitle:#"Result"
message:[NSString stringWithFormat:#"[SUCCESS!] Created Tweet with ID: %#", postResponseData[#"id_str"]]
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];*/
}
else {
NSLog(#"[ERROR] Server responded: status code %d %#", statusCode,
[NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
}
}
else {
NSLog(#"[ERROR] An error occurred while posting: %#", [error localizedDescription]);
}
});
};
//});
ACAccountStoreRequestAccessCompletionHandler accountStoreHandler =
^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"
#"/1.1/statuses/update_with_media.json"];
NSDictionary *params = #{#"status" : status};
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
[request addMultipartData:imageData
withName:#"media[]"
type:#"image/jpeg"
filename:#"image.jpg"];
[request setAccount:[accounts lastObject]];
[request performRequestWithHandler:requestHandler];
//});
}
else {
NSLog(#"[ERROR] An error occurred while asking for user authorization: %#",
[error localizedDescription]);
}
};
[accountStore requestAccessToAccountsWithType:twitterType
options:NULL
completion:accountStoreHandler];
}else
{
[[[UIAlertView alloc] initWithTitle:#"Wait"
message:#"Please Settigns > Twitter > In bottom Enable DealsHype to post"
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
}
}];
}
Hi I have create an event on Facebook through my iOS app by following code
-(void) createEvent:(NSString*)eventName Eventdesc:(NSString*)eventdesc EventDate: (NSString*)eventDate{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me/events"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
eventName, #"name",
eventdesc, #"description",
[NSString stringWithFormat:#"%#",[NSDate date]], #"start_time",
nil];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:meurl
parameters:params];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"event %#", meDataString);
if (!error) {
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"" message:#"Thanks for your support. Event has been created on your facebook page." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alertView show];
}else{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"" message:#"Unable to create event on facebook." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alertView show];
}
}];
}
Now I want to invite friends to this created event. I search lot but I did not get any helpful information.
please help. Thank you in advance.
You can invite users to an event by issuing an HTTP POST to /EVENT_ID/invited/USER_ID. You can invite multiple users by issuing an HTTP POST to /EVENT_ID/invited?users=USER_ID1,USER_ID2,USER_ID3. Both of these require the create_event permission and return true if the invite is successful.
Solving the problem by using follwing code
pragma mark- Invite Friends Method
-(void)inviteFriendsToEvent:(NSString*)eventID UserID:(NSMutableArray*)userID{
NSLog(#"ID=%#",[_IDArray lastObject]);
NSLog(#"Event ID:%#",_eventID);
NSData *data = [_eventID dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Event ID:%#",[json objectForKey:#"id"]);
NSURL *meurl = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/invited/%#",[json objectForKey:#"id"],[_IDArray lastObject]]];
//#"https://graph.facebook.com/EVENT_ID/invited?users=USER_ID1,USER_ID2,USER_ID3"
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Data=%#",meDataString);
}];
}
I have application with upload photo like in Instagram app. First my app uploads photo and returns link. Then sends link in status message. When I'm testing on my iPhone everything is ok, but when I'm testing on another iPhone then twitter return code 215 bad authentication data. Any ideas what could be wrong? Thx for reply.
- (void)tweet:(NSString *)identifier withCompletionHandler:(void (^)())completionHandler {
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) {
if (identifier) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 0) {
// Grab the initial Twitter account to tweet from.
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/update.json"];
NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"Check out this great flick on BLA BLA %#", [BLA_URL stringByAppendingFormat:#"/%#/%#", #"flick", identifier]]
forKey:#"status"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:dict];
[request setAccount:[accountsArray lastObject]];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
NSLog(#"TWEEET!");
}
else {
NSError *jsonError;
id data = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&jsonError];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Twitter response"
message:[NSString stringWithFormat:#"%d S: %d %#", [error code], [urlResponse statusCode], data]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
NSLog(#"NOOO TWEEET!");
[alertView show];
completionHandler();
});
}
}];
...
And Pre-checking function:
- (IBAction)twitterButtonTapped:(id)sender {
if ([self.twitterButton isSelected]) {
[self.twitterButton setSelected:NO];
}
else {
[self.twitterButton setSelected:YES];
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if (!granted) {
[self.twitterButton setSelected:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Twitter access"
message:#"Please make sure you have allowed twitter for BLA BLA in your Settings."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
}];
}
}
Ok, I've got the answer! Problem was that other iPhone has incomplete account data - meanings you have to has filled username and password in your Settings app.
I am trying to implement "Follow Us On Twitter" in my iOS app. Here is my code. But it give error "Could not prepare the URL request". Please help!
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore
requestAccessToAccountsWithType:accountType
options:NULL
completion:^(BOOL granted, NSError *error) {
if (granted) {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"a4arpan" forKey:#"screen_name"];
[tempDict setValue:#"true" forKey:#"follow"];
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"]
parameters:tempDict];
ACAccount * twitterAccount = [[ACAccount alloc] initWithAccountType:accountType];
twitterAccount.username = twitterUsername;
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData) {
if (urlResponse.statusCode >= 200 && urlResponse.statusCode < 300) {
NSError *jsonError;
NSDictionary *timelineData =
[NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingAllowFragments error:&jsonError];
if (timelineData) {
NSLog(#"Timeline Response: %#\n", timelineData);
}
else {
// Our JSON deserialization went awry
NSLog(#"JSON Error: %#", [jsonError localizedDescription]);
}
if ([urlResponse statusCode] == 200) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Follow us successfull" message:nil delegate:nil cancelButtonTitle:#"Thanx" otherButtonTitles:nil, nil];
[alert show];
}
else {
if ([tpAppMode isEqualToString:#"sandbox"])
NSLog(#"%#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Follow us Failed" message:nil delegate:nil cancelButtonTitle:#"Thanx" otherButtonTitles:nil, nil];
[alert show];
}
}
else {
// The server did not respond successfully... were we rate-limited?
NSLog(#"The response status code is %d", urlResponse.statusCode);
}
}
else {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %# %#", [error localizedDescription], [error localizedFailureReason]];
NSLog(#"%#", output);
}
}];
}
else {
if ([tpAppMode isEqualToString:#"sandbox"])
NSLog(#"%#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Follow us Failed" message:nil delegate:nil cancelButtonTitle:#"Thanx" otherButtonTitles:nil, nil];
[alert show];
}
}];
I have followed all the steps mentioned on Twitter Dev
That is how I've done it!
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"] parameters:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"AnatoliyGatt", #"true", nil] forKeys:[NSArray arrayWithObjects:#"screen_name", #"follow", nil]]];
[request setAccount:[[self twitterAccounts] lastObject]];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if(responseData) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if(responseDictionary) {
// Probably everything gone fine
}
} else {
// responseDictionary is nil
}
}];
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!");
}
}
}