© Radoslava Leseva Adams and Hristo Lesev 2016

Radoslava Leseva Adams and Hristo Lesev, Migrating to Swift from Flash and ActionScript, 10.1007/978-1-4842-1666-8_10

10. Getting Social: Posting to Facebook and Twitter

Radoslava Leseva Adams and Hristo Lesev2

(1)London, UK

(2)Kazanlak, Bulgaria

One of the significant events in the last decade was the rise of social networks. They transformed not only how we communicate with each other but also how ideas spread. If your app gives a compelling reason and an easy way for users to share thoughts and creations with their social network tribes, it can get the benefit of word of mouth and instantly be in front of the eyes of many more potential users.

In this chapter you will do the following:

  • Learn how to use the Social framework to post messages to Facebook and Twitter from your app.

  • Learn how to link a device with social media accounts.

  • Build an app that posts messages to Facebook and Twitter using the Social framework built-in composer user interface (UI).

When you are done, you will have an app that can post messages to the two most popular social networks: Facebook and Twitter. Note that to be able to test the app you will need Facebook and Twitter accounts.

Setting Up the App and Designing the UI

Apple recognized the power of the social media early on and introduced integration with Twitter as early as iOS 5. The next iOS release brought us the Social framework, which has continued to evolve since. In its current version the Social framework makes it easy to integrate several social network platforms with your app: Facebook, Twitter, Sina Weibo, and Tencent Weibo.

The app we are going to build will let the user compose and post messages with text and images to Facebook and Twitter. To do that we will use the built-in composer of the Social framework.

Create a Single View iOS application project (FileNewProject…, then iOSApplicationSingle View Application). Name it SocialSharingApp.

Open Main.storyboard and place two buttons and a text view on the main view of the app, as shown in Figure 10-1. Have a look back at Chapter 5 if you need a reminder for how to constrain the UI elements to make the design adapt to different screen sizes and orientations.

A371202_1_En_10_Fig1_HTML.jpg
Figure 10-1. The app's user interface

Next, open ViewController.swift and first import the Social framework at the top of the file. This will let us use the application programming interface (API) that posts to social networks.

Then create an outlet for the text view and name it postBody. Add actions for the two buttons’ Touch Up Inside events. (See Chapter 2 for how to create outlets and actions.) Name the first action postToFacebook and the second action postToTwitter.

Your code should look like that in Listing 10-1.

Listing 10-1. Adding an Outlet and Two Actions to the ViewController Class
import UIKit
import Social


class ViewController: UIViewController {

    @IBOutlet weak var postBody: UITextView!

    //The rest of the code goes here

    @IBAction func postToFacebook(sender: AnyObject) {
    }


    @IBAction func postToTwitter(sender: AnyObject) {
    }


}

We will see how to post not just text but also pictures to social media. To keep things simple, we will add an image to the app’s assets and include it in posts. If you did the tutorial in Chapter 5 , you already know how to add an image as an asset: in Xcode’s Project navigator open Asset.xassets, then drag and drop an image file inside (Figure 10-2). We will use the same cute panda image we used there (you can download it from https://pixabay.com/en/panda-bear-cute-happy-young-151587 ; rename the file to bear.png to keep it short).

A371202_1_En_10_Fig2_HTML.jpg
Figure 10-2. Adding a panda bear image to the project’s assets

Configuring Your Social Media Accounts on a Device

To be able to post a message to Facebook or Twitter from our app, the user must link iOS with his or her social media accounts first, using the device settings.

Stepping into the user’s shoes for a moment, let us do just that—you can use a device or one of the iOS simulators in Xcode. Go to Settings and find Facebook in the list. Tap it, enter your Facebook account details, and tap Sign In. On the next screen you will see a list of the ways that your device (or simulator) will be able to interact with your Facebook account. Tap Sign In again and you are ready. You can see the steps shown in Figure 10-3.

A371202_1_En_10_Fig3_HTML.jpg
Figure 10-3. Signing in with a Facebook account

Repeat the same steps to link your device (or the simulator) with Twitter. You can follow Figure 10-4.

A371202_1_En_10_Fig4_HTML.jpg
Figure 10-4. Signing in with a Twitter account

Before we continue with the back end of the application, make sure your device or the simulator is connected to both social networks. We will need that in order to share posts.

Composing and Posting a Facebook Post

The Social framework has standard composer user interface, which we will use. It is controlled by the SLComposeViewController class and offers several helper methods that are designed to assist with writing a post, adding an image, creating hyperlinks, and handling user interaction. In fact, this is quite similar to how we used the MessageUI framework to compose and send e-mail back in Chapter 9 .

Listing 10-1 will guide you through the implementation of posting a message on the user’s Facebook timeline. Open ViewController.swift, find the postToFacebook action we added earlier and let us begin.

The first thing we do is call isAvailableForServiceType(_:)—a method of SLComposeViewController, which checks if a Facebook account has been set up on the device. Note the use of the SLServiceTypeFacebook constant: isAvailableForServiceType(_:) handles several different social networks, so we must specify which one we are interested in. To tell the composer view controller that we are interested in working with Facebook we use SLServiceTypeFacebook.

If a Facebook account has been found, we set up an instance of SLComposeViewController and present it on the screen.

The setup includes optionally providing default content for the post by calling setInitialText, addImage and addURL. To use it with addImage, we wrap our cute panda picture in an instance of UIImage and load it from the app’s assets using its file name.

There is an interesting line towards the bottom of the listing: facebookVC’s property completionHandler takes a block of code, which will be executed when the user finishes working with the composer either by posting to Facebook or by cancelling the post. We will look at that syntax in detail when we discuss closures in Chapter 22 .

When all the setup is done the composer is shown on the screen with presentViewController.

Listing 10-2. Setting Up a Compose View Controller to Post to Facebook
@IBAction func postToFacebook(sender: AnyObject) {
    //Check if a Facebook account has been set up
    if false == SLComposeViewController.isAvailableForServiceType( ➤ SLServiceTypeFacebook ) {
        print("Facebook service is not available.")
        return
    }


    //Create an instance of the view controller,
    //which will show the post compoer on the screen
    let facebookVC = SLComposeViewController(
        forServiceType: SLServiceTypeFacebook)


    //Set post's message body
    facebookVC.setInitialText( postBody.text )
    //Add an image to the post
    facebookVC.addImage( UIImage(named: "bear") )


    //Add a url to the post
    let url = NSURL(string: "http://diadraw.com")
    facebookVC.addURL( url )


    //Handle post completion
    facebookVC.completionHandler = {
        result in


        switch result {
        case .Cancelled:
            print("Message cancelled.")
        case .Done:
            print("Message sent.")
        }
    }


    //Show facebookVC on the screen
    presentViewController(facebookVC, animated: false, completion: nil)
}
Note

You can add but also remove content from a post programmatically by calling removeAllImages and removeAllURLs. These are methods of the SLComposeViewController class.

Note also this line: facebookVC.completionHandler = { /*...*/ }. The curly brackets define a closure—a block of code that will be executed only after posting to Facebook completes. We will look at closures in detail in Chapter 22.

And that is all we need to do to allow the user to post to Facebook without leaving the app. Let us test it: run the application, fill in the message body, and tap the Post to Facebook button. The compose view controller will pop up as shown in Figure 10-5.

A371202_1_En_10_Fig5_HTML.jpg
Figure 10-5. Posting a message to Facebook from your application

Notice how you can tag your post with a geographical location and specify who can see it (define its audience). If the post contains an image, you can also add it to one of your Facebook photo albums.

Tap Post and open your Facebook account (use the Facebook app or a browser) to see the post with the smiling panda on your timeline (Figure 10-6).

A371202_1_En_10_Fig6_HTML.jpg
Figure 10-6. See the post on your Facebook timeline

Composing and Posting a Twitter Message

We will use the same idea and code structure to create a post for Twitter as we did for Facebook. The implementation of the postToTwitter action is shown in Listing 10-3.

We start by checking if a Twitter account has been set up on the device. If there is one available, we proceed with setting up the composer UI and presenting it on the screen. Note that this time we instantiate SLComposeViewController with SLServiceTypeTwitter.

Listing 10-3. Setting Up a Compose View Controller to Post to Twitter
@IBAction func postToTwitter(sender: AnyObject) {
    //Check if a Twitter account has been set up
    if false == SLComposeViewController.isAvailableForServiceType( å SLServiceTypeTwitter ) {
        print("Twitter service is not available.")
        return
    }


    //Create a composer view controller
    let twitterVC = SLComposeViewController(
forServiceType: SLServiceTypeTwitter)


    //Set post's message body
    twitterVC.setInitialText( postBody.text )
    //Add an image to the post
    twitterVC.addImage( UIImage(named: "bear") )


    //Add a url to the post
    let url = NSURL(string: "http://diadraw.com")
    twitterVC.addURL( url )


    //Handle post completion
    twitterVC.completionHandler = {
        result in


        switch result {
        case .Cancelled:
            print("Message cancelled.")
        case .Done:
            print("Message sent.")
        }
    }


    //Show twitterVC on the screen
    presentViewController(twitterVC, animated: false, completion: nil)
}

Let us test this. Run the app and tap the Post to Twitter button to see the composer UI show up on the screen (Figure 10-7). This being Twitter, you are limited to posts of up to 140 characters—notice how the Post button becomes inactive if you go over that count.

A371202_1_En_10_Fig7_HTML.jpg
Figure 10-7. Posting a message to Twitter from your application

If there is more than one Twitter account set up on the device, the composer UI will let the user choose which account to post to (Figure 10-8).

A371202_1_En_10_Fig8_HTML.jpg
Figure 10-8. Choosing to which of the active Twitter accounts to post

When you finish posting, you should see the new post in your Twitter account in a matter of seconds (Figure 10-9).

A371202_1_En_10_Fig9_HTML.jpg
Figure 10-9. See the post in your Twitter account

Other Types of Interaction with the Social Medias

Besides posting to the user’s timeline, the Social framework can help you with getting data back from social media platforms.

The SLRequest class can send HTTP requests to a social networking service. You can use it to retrieve user information from the HTTP API of each of the supported social media platforms. For example, you can send a request to Twitter and ask it to give you the activity feed for the currently logged in user.

Keep in mind that the SLRequest class is just a wrapper around the standard HTTP connection routines. The request endpoints and the format of the data returned by each social network service will be different.

Summary

In this chapter you used the built-in iOS functionality for sharing information on Facebook and Twitter. You learned about the Social framework and created an app that uses it to let users create posts with text, images, and hyperlinks on their social network timelines.

In the next chapter you will see how to access the device motion sensors, how to get a GPS location, and how to show it on a map.

..................Content has been hidden....................

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