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.

import Social

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

func tweetSLCVC() { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){ var twitterController:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) twitterController.setInitialText("Posting a tweet from iOS App" + "\r

" + "\r

" + "#Cool") twitterController.addImage(image) self.presentViewController(twitterController, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Twitter Account", message: "Please login to your Twitter account.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }

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

let image = UIImage(named: "RandomImage.jpg")

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

@IBAction func clickedSLCVC(sender: AnyObject) { tweetSLCVC() }

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.

import Accounts

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.

func tweetSLRSeparateMedia() { let account = ACAccountStore() let accountType = account.accountTypeWithAccountTypeIdentifier( ACAccountTypeIdentifierTwitter) account.requestAccessToAccountsWithType(accountType, options: nil, completion: {(success: Bool, error: NSError!) -> Void in if success { let arrayOfAccounts = account.accountsWithAccountType(accountType) if arrayOfAccounts.count > 0 { let twitterAccount = arrayOfAccounts.first as! ACAccount // Upload media first and use returned media_id_string in separate Tweet // Use media/upload.json to post GIF first let uploadURL = NSURL(string: "https://upload.twitter.com/1.1/media/upload.json") let url = NSBundle.mainBundle().URLForResource("Fish", withExtension: "gif") let imageData = NSData(contentsOfURL: url!) guard (imageData != nil) else {print("error: There is no imageData"); return} let uploadRequest = SLRequest(forServiceType:SLServiceTypeTwitter, requestMethod: .POST, URL: uploadURL, parameters: nil) uploadRequest.account = twitterAccount uploadRequest.addMultipartData(imageData, withName: "media", type: nil, filename: nil) uploadRequest.performRequestWithHandler() { (responseData: NSData!, urlResponse: NSHTTPURLResponse!, error: NSError!) -> Void in // Get the media_id_string from response let mediaIDString = self.stringForKey("media_id_string", fromJSONData:responseData) guard (mediaIDString != nil) else {print("error: no media id in response \(urlResponse.statusCode)"); return} let statusKey = "status" as NSString let mediaIDKey = "media_ids" as NSString // Use statuses/update.json for the tweet let statusURL = NSURL(string: "https://api.twitter.com/1.1/statuses/update.json") let message = "Posting a tweet with Animated GIF from iOS App" + "\r

" + "\r

" + "#Cool" // Separate request to post the tweet let statusRequest = SLRequest(forServiceType:SLServiceTypeTwitter, requestMethod: .POST, URL: statusURL, parameters: [statusKey : message, mediaIDKey : mediaIDString!]) statusRequest.account = twitterAccount statusRequest.performRequestWithHandler() { (responseData: NSData!, urlResponse: NSHTTPURLResponse!, error: NSError!) -> Void in if let err = error { print("error : \(err.localizedDescription)") } print("Twitter HTTP response \(urlResponse.statusCode)") } } } } else { let alert = UIAlertController(title: "Twitter Account", message: "Please login to your Twitter account.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }) } private func stringForKey(key: String, fromJSONData data: NSData?) -> String? { guard let inData = data else {return nil} do { let response = try NSJSONSerialization.JSONObjectWithData(inData, options: []) as? NSDictionary let result = response?.objectForKey(key) as? String return result } catch {return nil} }

Wire up the IBAction to call the new method.

@IBAction func clickedSLR(sender: AnyObject) { tweetSLRSeparateMedia() }

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.