Twitter Integration With Swift – Including Animated GIFs

This tutorial will cover integrating with Twitter using Swift so that we can post tweets with images. I’ll illustrate the simplest way to send tweets, and also discuss what needs to be done to support animated GIFs, which is a little more complicated.

Note: This tutorial is updated to work with the current Twitter API (as of January 2016) when tweeting with media using SLRequest.

The easiest method to send tweets is to use SLComposeViewController. However, currently if you want to include animated GIFs in a tweet, you need to use SLRequest and roll your own UI. I’ll show you how to use both methodologies. The code we’ll discuss is on my GitHub here, so feel free to incorporate it into your own projects.

To illustrate the concepts, we’ll trigger tweeting using a UIButton, so you’ll see in the code that I’ve added two buttons, one for SLComposeViewController and one for SLRequest. The two corresponding actions are also there, clickedSLCVC and clickedSLR.

We’ll begin with the implementation for SLComposeViewController. First, you need to import Social into your class.

Next we add the method to use SLComposeViewController. The code should be fairly self explanatory.

You’ll need to add an image to your class, which I’ve done as follows:

Finally, wire up the IBAction to call the method created above.

Build and run the app, then click on the Tweet SLCVC button. If you are not logged into Twitter, you’ll see the alert that you need to login to a Twitter account. Assuming you are logged in, you’ll see the Twitter screen as shown below from my iPhone 6 Plus.


Click post, head over to your Twitter app, and you’ll see the tweet along with the image.

Let’s take a look now at using SLRequest so that we can tweet with animated GIFs. We need to add another import.

Add the following methods to use SLRequest and post the included Fish.gif along with the Tweet. Note that Twitter deprecated the original method of accomplishing this, so now two steps are required, one to upload media, then the second step to post the tweet with media. This is updated since I originally published this article, and the code in GitHub is updated accordingly.

Wire up the IBAction to call the new method.

Build and run the app, and the tweet will be posted, including the animated GIF, without using a user interface.

In production you’d want some more error handling, so treat this as an example of how to tweet with media.

You’ll notice we supply an instance of NSData versus UIImage to the addMultipartData method.

That concludes this tutorial. I hope it helps you integrate your iOS app with Twitter. If you have comments, suggestions, or any general feedback, feel free to leave a comment or send me an email.

Leave a Comment:

Add Your Reply