Composing a tweet

In this recipe, we will look at how we can use the Twitter APIs for iOS 5 and interact with them effectively.

Getting ready

Twitter has provided us with some very simple APIs to follow, making it a snap to interact with them. In this recipe, we will look at how we can use these to post a tweet using the Twitter composition sheet.

How to do it…

In order to use Twitter within your application, we need to add the Twitter framework to your project. This can be achieved by performing the following simple steps:

  1. Select your project from within the project navigator.
  2. Then, select your project target from under the TARGETS group.
  3. Select the Build Phases tab.
  4. Expand the Link Binary with Libraries disclosure triangle.
Click on the + button and select Twitter.framework from the list.
  5. Finally, click on the Add button to add the framework to your project.

Our next step is to create the code functionality that will be responsible for posting our tweet to Twitter:

  1. Open the ViewController.m implementation file from the project navigator.
  2. Type in the following import statements:
    #import <Twitter/Twitter.h>
    
  3. Next, modify the composeTweet method, as shown in the following code snippet:
    - (IBAction)composeTweet:(id)sender {
        
      TWTweetComposeViewController *myTwitter = 
    [[TWTweetComposeViewController alloc] init];
      
    BOOL isSUCCESS = TWTweetComposeViewController.canSendTweet;
      if (isSUCCESS == YES)
      {
        [myTwitter setInitialText:@"Welcome to Twitter API."];
        [self presentModalViewController:myTwitter 
    animated:YES];
          
        // Retrieve the result of the Twitter handler to 
          // determine if the message was successfully sent.
        myTwitter.completionHandler = 
    ^(TWTweetComposeViewControllerResult res)
          {
        if (res == TWTweetComposeViewControllerResultDone) 
    {
          UIAlertView *alertView = [[UIAlertView alloc] 
    initWithTitle:@"Success" message:@"Your tweet was 
    posted successfully." delegate:self 
    cancelButtonTitle:@"OK" otherButtonTitles:nil];
          [alertView show];
          [self dismissModalViewControllerAnimated:YES];
        }
        else if (res == 
    TWTweetComposeViewControllerResultCancelled) {
            UIAlertView *alertView = [[UIAlertView alloc] 
    initWithTitle:@"Error" message:@"Tweet not 
    posted." delegate:self cancelButtonTitle:@"OK" 
    otherButtonTitles:nil];
            [alertView show];
          [self dismissModalViewControllerAnimated:YES];
          }
        };
      }
    }

How it works...

Starting with iOS 5, whenever you want to compose a Twitter message for submission, you will need to use the TWTweetComposeViewController class instance. The TWTweetComposeViewController class handles everything, and presents us with a tweet composition sheet, so that we can begin to type in our tweet.

The TWTweetComposeViewController class also enables you to set the initial Twitter text information to use, including how to go about adding images and URLs. Next, we declared a myTwitter variable to point to an instance of our TWTweetComposeViewController class.

We then used the canSendTweet class method of the TWTweetComposeViewController class to check to see if the user has correctly installed and set up Twitter. If this has not been done, this statement will fail, and a value of NO (or FALSE) will be returned to the isSuccess variable.

Next, we assigned some text to appear on our composition sheet, by setting the setInitialText method, and then displayed this to the view. Finally, we set up a handler, using the completionHandler method to notify us when the user has completed composing the tweet and display the relevant alert message based on the outcome returned by the method.

Note

For more information on the TWTweetComposeViewController class, you can refer to the Twitter framework reference documentation, located at https://developer.apple.com/library/ios/#documentation/Twitter/Reference/TWTweetSheetViewControllerClassRef/Reference/Reference.html.

There's more…

With the release of iOS 6, integration of social networks is performed through the use of the UIActivityViewController class, or the classes that are contained with the new social framework of the iOS 6 SDK. For general-purpose social networking integration, the UIActivityViewController class is the recommended path.

When using this class, the user is presented with a screen providing a choice of social network services. Once the application has selected a target service, the class then presents the user with a blank message preview panel where the message can be reviewed and then posted.

Next, we will take a look at both the UIActivityViewController and SLComposeViewController classes to see each of their differences.

Using the UIActivityViewController class

The UIActivityViewController class is instantiated from within an application at the point when posting is ready to be made to a social network. The following code snippet shows how to use the UIActivityViewController class to handle posts to Twitter:

NSString *postText = @"My first Twitter Post from iOS 6";
NSArray *activityItems = @[postText];

UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];

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

The preceding code snippet instantiates a new UIActivityViewController instance, and passes the text to be included within the dialog box when it is presented to the user. There is an option to include an image with the post, which we will be taking a look at a bit later.

Once the user decides to take an action to post an update from within an application, the following screen is displayed:

Using the UIActivityViewController class

Once a destination social network has been selected from the list of choices, a preview sheet will be displayed. In the event that the user has not yet configured an account for the selected social network in the Settings application, a dialog box will appear providing the user to either set up an account or simply cancel the posting.

Note

For more information on the UIActivityViewController class, you can refer to the Apple Developer reference documentation, located at https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityViewController_Class/Reference/Reference.html.

Using the SLComposeViewController class

In order to use the SLComposeViewController class, a number of steps are required to be performed. First, we need to verify whether the message can be sent to the specific social network service to ensure that the device has been properly configured to use the particular service.

This is achieved by passing through the type of service as an argument to the isAvailableForserviceType method, as shown in the following code snippet:

if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
      // Device has been set up to use Twitter
}

The isAvailableForServiceType method accepts the following parameters:

  • SLServiceTypeFacebook
  • SLServiceTypeTwitter
  • SLServiceTypeSinaWeibo

The next step is to create an instance of the SLComposeViewController class and supply an optional completion handler to be called when the compose sheet is either cancelled by the user or used to send a message. Finally, when the message is ready to be presented to the user, the SLComposeViewController object is presented modally by calling the presentViewController method of the parent view controller.

The following code snippet shows how to configure and present the SLComposeViewController class instance for posting to Twitter:

SLComposeViewController *composeController = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
    
[composeController setInitialText:@"Posting using Twitter"];
[composeController addURL: [NSURL URLWithString:
@"http://www.packtpub.com/xcode-4-cookbook/book/"]];
    
[self presentViewController:composeController
               animated:YES completion:nil];

The preceding code snippet presents you with the Twitter compose sheet with the default text preconfigured using the method calls. The completion handler can be set up to pass a value back, indicating the action taken by the user within the compose sheet view. These values are explained in the following table:

Compose sheet values

Description

SLComposeViewControllerResultCancelled

The user cancelled the composition session by touching the Cancel button.

SLComposeViewControllerResultDone

The user sent the composed message by touching the Sent button.

The social framework class that comes with iOS 6 contains two classes that have been designed to provide more flexibility around social networking integration.

The SLComposeViewController class, unlike the UIActivityViewController class, allows you to post a message to a specific social network service within the application code, without requiring the user to make a selection from the list of available services.

The user is then presented with a preview sheet appropriate to the specific service the application has been set up for. Using the social framework within your application is very simple, and can be achieved by performing the following simple steps:

  1. Add Social.framework into your project similarly as we did with Twitter.framework.
  2. Open the ViewController.m implementation file from the project navigator.
  3. Type in the following import statement:
    #import <Social/Social.h>
    
  4. Next, modify the composeTweet method, as shown in the following code snippet:
    - (IBAction)composeTweet:(id)sender {
      
      if ([SLComposeViewController 
    isAvailableForServiceType:SLServiceTypeTwitter])
      {
      // Device is able to send a Twitter message
      SLComposeViewController *composeController = 
    [SLComposeViewController
    composeViewControllerForServiceType:SLServiceTypeTwitter];
        
      SLComposeViewControllerCompletionHandler 
        __block myHandler = 
    ^(SLComposeViewControllerResult result) {
          if (result == SLComposeViewControllerResultDone) {
            UIAlertView *alertView = [[UIAlertView alloc] 
    initWithTitle:@"Twitter"
      message:@"Yourtweet was posted successfully."
    delegate:self
    cancelButtonTitle:@"OK"
    otherButtonTitles:nil];
            [alertView show];
          }
          else if (result == 
    SLComposeViewControllerResultCancelled) {
            UIAlertView *alertView = [[UIAlertView 
    alloc] initWithTitle:@"Twitter"
      message:@"Your Tweet was not posted."
    delegate:self
    cancelButtonTitle:@"OK"
    otherButtonTitles:nil];
            [alertView show];
          }
          [composeController dismissViewControllerAnimated:YES 
    completion:nil];
        };
        
        [composeController setCompletionHandler:myHandler];
        [composeController setInitialText:@"Welcome to iOS 6"];
        [composeController addURL: [NSURL URLWithString:
      @"http://www.packtpub.com/xcode-4-cookbook/book/"]];
        
        [self presentViewController:composeController
                   animated:YES completion:nil];
      }
    }

    Note

    For more information on the SLComposeViewController class, you can refer to the Apple Developer reference documentation, located at https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html.

See also

  • The Adding photos to a Tweet recipe
  • The Presenting storyboard view controllers programmatically recipe
  • The Understanding the Core Motion framework section in Appendix, Exploring the Multi-touch Interface
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset