2

I'm using below code to share the content (from UITextView, UIImageView) through twitter

-(void)shareViaTweet:(NSString *)shareMessage{
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
    SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [tweetSheet setInitialText:[NSString stringWithFormat:@"%@",shareMessage]];
    if (self.imageString)
    {
        [tweetSheet addImage:[UIImage imageNamed:self.imageString]];
    }

    if (self.urlString)
    {
        [tweetSheet addURL:[NSURL URLWithString:self.urlString]];
    }
    [self presentViewController:tweetSheet animated:YES completion:nil];
}
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];
}

}

But I need share this, without using the pop up view (I think tweet sheet). It's happening because the below code,

[self presentViewController:tweetSheet animated:YES completion:nil];

When I click the button "Share" of my app, I need to post that in twitter.

Edited:

- (IBAction)doneButtonClicked:(id)sender
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSString *message = messageTextView.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); //in this u can get all accounts user names provide some UI for user to select,such as UITableview
}


NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"
              @"/1.1/statuses/user_timeline.json"];
             NSDictionary *params = @{@"screen_name" : message,
                                     @"forKey":@"status",
                                      @"trim_user" : @"1",
                                      @"count" : @"1"};
// Request access from the user to access their Twitter account

[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)

 {
     if (granted == YES)
     {
         // Populate array with all available Twitter accounts
         NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
         if ([arrayOfAccounts count] > 0)
         {
             //use the first account available
             ACAccount *acct = [arrayOfAccounts objectAtIndex:0]; //hear this line replace with selected account. than post it :)




             SLRequest *request =
             [SLRequest requestForServiceType:SLServiceTypeTwitter
                                requestMethod:SLRequestMethodPOST
                                          URL:url
                                   parameters:params];


             //Post the request
             [request setAccount:acct];

             //manage the response
             [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
              {
                  if(error)
                  {
                      //if there is an error while posting the tweet
                      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"Error in posting" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                      [alert show];

                  }
                  else
                  {
                      // on successful posting the tweet
                      NSLog(@"Twitter response, HTTP response: %i", [urlResponse statusCode]);
                      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"Successfully posted" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                      [alert show];


                  }
              }];

         }
         else
         {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"You have no twitter account" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
             [alert show];

         }
     }
     else
     {
         //suppose user not set any of the accounts
         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"Permission not granted" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
         [alert show];

     }
 } ];


//[widgetsHandler closeWidget:nil];


//[self postImage:shareImageView.image withStatus:messageTextView.text];
}

Update: Error

enter image description here

Chanuka
  • 199
  • 1
  • 2
  • 15

2 Answers2

4

To send images u need do something like this


  [account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
 {
   if (granted == YES)
    {
      // Populate array with all available Twitter accounts
     NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
     if ([arrayOfAccounts count] > 0)
      {
           //use the first account available
       ACAccount *acct = [arrayOfAccounts objectAtIndex:0];

       //create this request 
       SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL   URLWithString:@"https://api.twitter.com"@"/1.1/statuses/update_with_media.json"] parameters:  [NSDictionary dictionaryWithObject:message forKey:@"status"]];
       UIImage *imageToPost = [UIImage imageNamed:@"image.jpg"];
       NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0f);//set the compression quality
      [postRequest addMultipartData:imageData withName:@"media" type:@"image/jpeg" filename:@"image.jpg"];

   //set account and same as above code 

....
 ....


Shankar BS
  • 8,394
  • 6
  • 41
  • 53
  • It's giving me an error, see the edits. I go through [this](http://stackoverflow.com/questions/6778167/undocumented-nsurlerrordomain-error-codes-1001-1003-and-1004-using-storeki0) link. Yes, it's take lot more time to come to that error in debugging. I don't know how to fix it. – Chanuka Sep 26 '13 at 05:50
  • did u set up all URLSchemes – Shankar BS Sep 26 '13 at 06:00
  • It worked perfectly for me and i posted that code. It should work try a test project and post from it and see if it is posting or not – Shankar BS Sep 26 '13 at 07:00
  • Where do I need to put consumer key, consumer secret codes in my application. May be that will be the problem. – Chanuka Sep 26 '13 at 07:08
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38078/discussion-between-shan-and-user2745507) – Shankar BS Sep 26 '13 at 07:11
1

if u wanna share the tweet without using the tweet sheet see my answer it will post on twitter wall without using the tweet sheet see hear and also set the twitter account in the device. hope this helps

unfortunately the class TWRequest is deprecated in iOS 6 but alternatively we can use SLRequest present in the Social framework

the answer for this is similar to the old answer i commented out something that i dont want but if u want to select which account to use then uncomment the commented code


 - (IBAction)doneButtonClicked:(id)sender
    {
      ACAccountStore *account = [[ACAccountStore alloc] init];
      ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
      NSString *message = _textView.text;

    //    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"]);
    //        NSLog(@"user_id  =  %@",[details objectForKey:@"user_id"]);
    //    }


    // Request access from the user to access their Twitter account
    [account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
    {
        if (granted == YES)
        {
         // Populate array with all available Twitter accounts
            NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
            if ([arrayOfAccounts count] > 0)
             {
               //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:message forKey:@"status"] requestMethod:TWRequestMethodPOST]; //commented the  deprecated method of TWRequest class

             SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:message forKey:@"status"]]; //use this method instead



             //Post the request
             [postRequest setAccount:acct];//set account

             //manage the response
             [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
              {
                 if(error)
                  {
                      //if there is an error while posting the tweet
                      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"Error in posting" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                      [alert show];
                      [alert release];
                  }
                  else
                  {
                      // on successful posting the tweet
                      NSLog(@"Twitter response, HTTP response: %i", [urlResponse statusCode]);
                      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"Successfully posted" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                      [alert show];
                      [alert release];

                  }
              }];

         }
         else
         {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"You have no twitter account" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
             [alert show];
             [alert release];
         }
     }
     else
     {
         //suppose user not set any of the accounts
         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Twitter" message:@"You have no twitter account" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
         [alert show];
         [alert release];
     }
 } ];

[account release];

 }


Community
  • 1
  • 1
Shankar BS
  • 8,394
  • 6
  • 41
  • 53
  • The method name, `[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)` and `TWRequest *postRequest = [[TWRequest alloc] initWithURL: [NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:message forKey:@"status"] requestMethod:TWRequestMethodPOST];` are deprecated, can you help me with that? – Chanuka Sep 06 '13 at 06:34
  • did u added #import #import #import #import all these headers and also frameworks – Shankar BS Sep 06 '13 at 06:36
  • ya, but this is the way without using tweet sheet that i followed. – Shankar BS Sep 06 '13 at 06:38
  • try setting "SLRequestMethodPOST" in ur code. U are using "SLRequestMethodGET" – Shankar BS Sep 06 '13 at 09:36
  • No, But it says "Successfully posted" Do I need to add Twitter App ID or something else where. See the edits. – Chanuka Sep 09 '13 at 04:52
  • Code is working perfectly, it identify the users also. but the post is not there. Do I need to login to the twitter, inside from my app? Your is greatly appreciated – Chanuka Sep 25 '13 at 04:52
  • No need to login to account it just will just post. – Shankar BS Sep 25 '13 at 05:36
  • wait i tested it using "SLRequest" it is posting successfully and i got posted message perfectly wait i will post my code – Shankar BS Sep 25 '13 at 05:38
  • @user2745507 let me know if u are facing any problem – Shankar BS Sep 25 '13 at 06:00
  • Great,Thanks @Shan, It work perfectly. There's a thing, can you help me with attaching an image(s) to this post. – Chanuka Sep 25 '13 at 10:14
  • Hmm wait i will check – Shankar BS Sep 25 '13 at 10:15
  • i posted the new answer for posting images and i am also suggesting u to go through this https://dev.twitter.com/docs/ios/posting-images-using-twrequest – Shankar BS Sep 25 '13 at 10:59