Getting Social: An Introduction to Integrating Twitter and Facebook Into Your iOS Applications

With an increasing number of apps in the App Store, a major challenge for App Developers is how to get their application noticed. Traditionally, developers have turned to advertising, spending their hard earned cash on in-app and mobile advertising to drive demand. In recent years though, cost effective alternatives have come to the fore and can play a major role in the success of your application.

As you probably know, social media is here to stay. The number of people using social networks such as Facebook and Twitter continues to grow year on year and their importance as both a marketing tool and as a way of building and connecting with your apps user base cannot be underestimated. So what choices does a developer wanting to integrate social networking into their application have?

Prior to iOS 5, the choices were limited. Before this point, libraries were available from both Twitter and Facebook that would enable developers to incorporate social networking features, but using them was not straightforward and it often took a significant amount of work to get them successfully integrated. In turn this often led to pain and frustration and many developers would simply give up, missing out on the benefits that social networking could bring to their apps. With the arrival of iOS 5, though, all this changed.

With iOS 5, Apple built social networking right into the operating system. Along with it, Apple made a new Social Framework available to developers. The Social Framework built on the functionality within iOS and provided a number of tools that allowed developers to easily integrate Twitter into their applications. Apple continued to build on this functionality in iOS 6, and further enhanced the Social Framework with support for both Facebook and Sina Weibo, an extremely popular Chinese microblogging platform.

In this post we're going to take a look at this framework and investigate the basics of incorporating social networks within your apps. We'll do this by writing a demo application of our own, one that lets users send Tweets and Share things on Facebook, all without leaving the app. Let's make a start.

Creating the Application

Open up Xcode and once it’s started, press ⇧⌘N or select File > New Project to create a new project. When prompted, select the Single View Application Template and then select Next.

When prompted, enter SocialFrameworkDemo as the Product Name, iOS Development Tutorials as the Organization Name and set com.iosdevelopmenttutorials as the Company Identifier. Enter IDT as the class prefix and select iPhone as the Device before selecting Next.

Make your own choice about whether or not to create a Git Repository, and then save your new project by selecting the Create button.

Adding the Required Frameworks

Having created our project, the first thing we need to do is to add the Social.framework. In the project navigator make sure you have the SocialFrameworkDemo project selected. Xcode will in turn show the Project Settings. To the left side of the settings window, select the SocialFrameworkDemo target in the Projects and Targets List or alternatively, if the Project and Targets List is not displayed, select the SocialFrameworkDemo target from the drop-down list. With the SocialFrameworkDemo target settings displayed, scroll down to the bottom of the page until you can see the Linked Frameworks and Libraries section.

The Frameworks and Libraries Section in Xcode

At the bottom of the list of frameworks, select the + button. In the search field of the pop-up window, enter Social.framework. Xcode will filter the list of frameworks based on your search term. Select the Social.framework once it is displayed and then select the Add button to add the framework to our project.

Creating the User Interface

Now that we have the required frameworks linked into our project, let's create the user interface for our app.

For the purposes of this demo, our user interface is going to be extremely simple. We're just going to have a single button. When pressed, the button will display a UIActionSheet which will contain three further buttons. These latter three buttons will allow the user to either send a Tweet, Share on Facebook or Cancel.

Adding the Button

In the project navigator select the Main.storyboard file. Bring up the Object Library by pressing ⌃⌥ ⌘3 or selecting View > Utilities > Show Object Library from the menu. Select a UIButton instance from the Object Library and drag it onto the view in the storyboard.

Use the guides and resize handles to center it in the middle of the view and resize it to take up the full width of the view. With the button selected, select the Align button (The Align Button) in the bottom-right hand corner of the Interface Builder window.

From the alignment pop-up make sure the check boxes next to Horizontal Center in Container and Vertical Center in Container are both checked and the offsets are set to zero. Once done, select the Add 2 constraints button.

Next, select the Pin button (The Pin Button) in the bottom right of the Interface Builder screen. From the pop-up, set the leading and trailing space for the button to 20 points and set the checkbox next to the height constraint, pinning the button to 30 points in height. Once done, select the Add 3 constraints button.

With the constraints all set, double-click on the button and change the title to Share. In the next section, we'll hook our button up to our code.

The Social Framework Demo User Interface

Connecting the User Interface to the Code

Bring up the Assistant Editor by selecting ⌥ ⌘⏎ or by selecting View > Assistant Editor > Show Assistant Editor.

In the Assistant Editor, make sure the IDTViewController.m file is displayed.

Hold down the Ctrl key, and then click and drag from the button we just added to the IDTViewController.m file and move the cursor to a point just below the didReceiveMemoryWarning method. You should see Xcode display a blue line and an Insert Action prompt. At this point you can release the mouse button. Xcode will then display a new pop-up.

In the pop-up, ensure the Connection is set to Action. For the Name enter share and for the Type enter UIButton. Ensure that Event is set to Touch Up Inside and the Arguments is set to Sender, and then select the Connect button.

With that, we're done with setting up our user interface. Save the interface builder file by pressing ⌘S or by selecting File > Save.

Implementing the Code

With our user interface now connected, we'll make a start on the code. First we're going to tackle displaying the UIActionSheet instance. There are a number of elements to this.

First we're going to write the necessary code within the share: method we created earlier.

When this method is invoked (by the button on our user interface), we will display a UIActionSheet instance configured to display three buttons; one that will allow the user to send a Tweet, one that will allow them to Share on Facebook and one that will allow them to Cancel.

We'll then tell the compiler that the IDTViewController class will implement the required methods from the UIActionSheetDelegate protocol before implementing the actionSheet:clickedButtonAtIndex: delegate method. The actionSheet:clickedButtonAtIndex: method is called when the user selects a button from the displayed UIActionSheet.

Within the actionSheet:clickedButtonAtIndex: method, there will be three courses of action.

If the user presses the Cancel button, we will simply dismiss the UIActionSheet. This is done automatically by the UIActionSheet class so we shouldn't have to write any code to implement this one.

The latter two will however require code. If the user presses either the Tweet button or the Share on Facebook button, we will create an instance of SLComposeViewController, a ready made class provided within the Social.framework that will allow our user to compose and send to the relevant social network.

This class will deal with all the intricacies of connecting to the relevant social network and sending our Tweet / Post or allowing the user to Cancel. All we will do is check to see whether the post was sent or not and log the outcome. In your own app, you might choose to implement something more complex but this will at least head you in the right direction. Let's make a start.

Displaying the UIActionSheet

Select the IDTViewController.m file in the project browser and scroll to the top of the file. Modify the private interface declaration as follows:

@interface IDTViewController () <UIActionSheetDelegate>

This tells the compiler that the IDTViewController is going to implement one or more UIActionSheetDelegate methods and allows us to set the IDTViewController as the delegate for the UIActionSheet instance. We'll do that next.

With the IDTViewController.m file still selected scroll down to the share: method we added in the previous section. Inside the method add the following code:

UIActionSheet *sharingSheet = [[UIActionSheet alloc] initWithTitle:@"Share"
                               delegate:self
                               cancelButtonTitle:@"Cancel"
                               destructiveButtonTitle:nil
                               otherButtonTitles:@"Tweet", 
                               @"Share on Facebook", nil];
[sharingSheet showInView:self.view];

In the first line, we create our UIActionSheet. As you can see, the initializer for the UIActionSheet takes a number of parameters.

First we supply the title for the UIActionSheet which is a simple string. In this case we call it Share. We then set the delegate to the IDTViewController class by setting the delegate to self. This is possible because of the steps we took just now to inform the compiler that we would implement the UIActionSheetDelegate methods.

We also set the title of the Cancel button to (not surprisingly) Cancel and set the destructive button title to nil. We then supply a list of titles for any additional buttons that we need. For the purposes of our demo app, we only need two; one for sending a Tweet and one to Share on Facebook.

In the second line, we then display the UIActionSheet instance by calling the showInView: method and supplying the IDTViewController's view.

Implementing the UIActionSheet Delegate Method

With the IDTViewController.m file still selected, add the following code to the bottom of the file:

#pragma mark - UIActionSheetDelegate Methods

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (index == 0)
    {
        NSLog(@"Tweet Button Pressed.");
    }
    else if (index == 1)
    {
        NSLog(@"Share on Facebook Button Pressed.");
    }
}

The contents of this function are pretty simple.

When the method is called, we check the index of the button that was pressed. Based on the index we then log whether the user pressed the Tweet button or the Share on Facebook button. To check that we have everything hooked up properly, save the file by pressing ⌘S or by selecting File > Save and then build and run your application.

Once the app has started, press the Share button. You should see the UIActionSheet displayed. Select the Cancel button. The UIActionSheet should be dismissed. Press the Share button again. This time, select the Tweet button and pay attention to the Console Output in Xcode. You should see the log message indicating that the Tweet button was pressed. Repeat this and check that the Share on Facebook button is also detected.

If everything was successful, we'll move on and look at writing the code to send a Tweet.

Implementing Twitter Support

Within the actionSheet:clickedButtonAtIndex: method, add the following code after the NSLog statement inside the first clause of the if statement:

// Twitter
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
    SLComposeViewController *tweet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [tweet setInitialText:@"I just completed the Social.framework Tutorial by @iosdevtutorials !"];
    [tweet setCompletionHandler:^(SLComposeViewControllerResult result)
    {
        if (result == SLComposeViewControllerResultCancelled)
        {
            NSLog(@"The user cancelled.");
        }
        else if (result == SLComposeViewControllerResultDone)
        {
            NSLog(@"The user sent the tweet");
        }
    }];
    [self presentViewController:tweet animated:YES completion:nil];
}
else
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Twitter"
                          message:@"Twitter integration is not available.  A Twitter account must be set up on your device."
                          delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    [alert show];
}

In line 2, we check whether the Twitter service is available as part of the condition for the if statement.

As I mentioned earlier, the Social.framework builds on the Twitter and Facebook functionality baked into iOS and to be able to successfully post to Twitter, the user must have already setup a Twitter account on their device. The isAvailableForServiceType: method of the SLComposeViewController class is a convenient way of assessing whether a particular service is available, returning true if the user has setup an account for the service and false otherwise.

The isAvailableForServiceType: method takes a single parameter indicating the type of service we want to know about and in this case, we supply one of the constants defined by the Social.framework (SLServiceTypeTwitter) to indicate that we are interested in whether the user has setup a Twitter account.

Based on the information returned, we take one of two courses of action.

If an account is available, in line 4 we create an instance of the SLComposeViewController class by calling the composeViewControllerForServiceType: method. We again supply the SLServiceTypeTwitter constant to indicate to the SDK that we want our SLComposeViewController instance connected to Twitter.

With the instance of the SLComposeViewController created, on line 5 we set the initial placeholder text for the SLComposeViewController instance. The user can edit this text but it provides a useful way for us to pre-populate the fields on their behalf.

In line 6 we then set the completion handler for the SLComposeViewController instance by calling the setCompletionHandler: method. The completion handler is called by the SLComposeViewController instance when the view is dismissed by the user (either by sending the Tweet or by Cancelling). The method takes a single block parameter and inside the block we simply log whether of not the user sent the Tweet or Cancelled.

On line 17 we then present the SLComposeViewController instance, displaying it to the user.

Lines 19 - 23 represent our alternative course of action. This is the path taken if the Twitter service is not available on the device. For our demo app, we keep this simple and create and present an instance of the UIAlertView class, which we use to indicate to the user that they must set up a Twitter account on the device before they can send Tweets.

Next, we'll look at adding Facebook support. As you will see, the steps involved are surprisingly familiar.

Implementing Facebook Support

Scroll to the bottom of the actionSheet:clickedButtonAtIndex: method and in the else if (index == 1) clause add the following code after the NSLog statement:

// Facebook
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
    SLComposeViewController *tweet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    [tweet setInitialText:@"I just completed the Social.framework Tutorial by @iosdevtutorials !"];
    [tweet setCompletionHandler:^(SLComposeViewControllerResult result)
    {
        if (result == SLComposeViewControllerResultCancelled)
        {
            NSLog(@"The user cancelled.");
        }
        else if (result == SLComposeViewControllerResultDone)
        {
            NSLog(@"The user posted to Facebook");
        }
    }];
    [self presentViewController:tweet animated:YES completion:nil];
}
else
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Facebook"
                          message:@"Facebook integration is not available.  A Facebook account must be set up on your device."
                          delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    [alert show];
}

As you can see, the code here is almost identical to that for sending a Tweet. Apart from some cosmetic differences in the alert view we display and in what we log, the only major difference is that we use the SLServiceTypeFacebook constant when checking whether the Facebook is available and in subsequently creating an instance of the SLComposeViewController class.

That's it. It's that easy. That's all we need to change to Post to the user's Facebook wall rather than Twitter. All the differences are hidden within the SLComposeViewController instance.

Testing the Application

With everything done, let's fire up our app and check that everything is working.

Save the IDTViewController.m file by pressing ⌘S or by selecting File > Save and then build and run your application.

As before, select the button on the user interface and then select either the Tweet or Share on Facebook button. Depending on whether you have an account for the relevant social network set up on your device, you will see either the UIAlertView instance or the SLComposeViewController instance.

Social Framework Demo ActionSheetSending a Tweet using SLComposeViewController

Remember, to successfully send a Tweet or Share on Facebook, you must have accounts already set up on your device, whether that's a physical device or in the simulator. This can be done easily by opening the Settings app on the device and scrolling down to either the Twitter or Facebook entries and following the instructions.

Adding a social network account in the settings app

Where Next

In this article we've seen just how easy it is to integrate social networking for Twitter and Facebook into your applications and we've seen how the SLComposeViewController class provides a simple and clean way for interfacing with these services with the minimum of hassle.

This is not the only option though. For more advanced usage, the Social Framework also provides the SLRequest class. This class provides lower level access and a greater amount of flexibility than the SLComposeViewController class and for those of you who need a more customized approach it can be a great way to go. Check out the documentation on the SLRequest class here.

Getting in Touch

That's it for this article. If you need more help, the source code for our demo app is available from the iOS Development Tutorials page on GitHub.

Let me know your reactions in the comments, and keep an eye out for my next tutorial on Binpress. Happy coding!

0 comments


Or enter your name and Email
No comments have been posted yet.