Twitter iOS Tutorial

With the Social Framework it is possible to use social media from inside an App. In this tutorial we will pick an image from the Photo Library and tweet a message including the image to Twitter. This tutorial is made with Xcode 8.2.1 and built for iOS 10.2.

Open Xcode and create a new Single View Application.

For product name, use IOS10TwitterTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard. Drag an Image View to the main View.  Select the Image View and go to the Attributes inspector. In the View section give the view a mode of "Aspect Fit".

This mode will fit the image into the Image View. Next, add two Buttons to the view and place them below the Image View. Give them a title of "Choose Image" and "Tweet" .

Select the Image View and select the Pin button from the Auto Layout button on the bottom-right of the Storyboard and fill in the following values. Select Add 4 Constraints.

Hold down the Ctrl key and select the "Choose Image" and "Tweet" button. Select the Align button on the bottom-right of the Storyboard and choose "Horizontally in Container". Select "Add 2 Constraints".

Select the "Choose Image" button and select the Pin button from the Auto Layout button on the bottom-right of the Storyboard and pin the button to the left. Select Add 1 Constraint.

Select the "Tweet" button and select the Pin button from the Auto Layout button on the bottom-right of the Storyboard and pin the button to the right. Select Add 1 Constraint.

The Storyboard should look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Image View to the ViewController class and create the following Outlet.

Ctrl + drag from the Choose Image Button to the ViewController class and create the following Action.

Ctrl + drag from the Tweet Button to the ViewController class and create the following Action.

To use the Social framework we will have to import it to the project. Add the following line to the top of the ViewController.swift file.

import Social

The ViewController needs to conform to the UINavigtionControllerDelegate and the UiImagePickerControllerDelegate to use the Photo Library. Change the declaration line to

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

Add the following property to the class

var pickerController: UIImagePickerController = UIImagePickerController()

Next, implement the chooseImagePressed method

@IBAction func chooseImagePressed(_ sender: Any) {
        
    // 1
    pickerController.delegate = self
    pickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
        
    // 2
    self.present(pickerController, animated: true, completion: nil)
}
  1. Set the delegate to the View Controller and set the sourceType to the Photo Library
  2. Present the Image Picker Controller.

Next, we will implement the tweetButtonPressed method to create the tweet sheet.

@IBAction func tweetButtonPressed(_ sender: Any) {
        
    // 1
    if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) {
            
        // 2
        let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
            
        // 3
        if let tweetSheet = tweetSheet {
            tweetSheet.setInitialText("Look at this nice picture!")
            tweetSheet.add(imageView.image)
                
            // 4
            self.present(tweetSheet, animated: true, completion: nil)
        }
    } else {
            
        // 5
        print("error")
    }
}
    

Let's take a look at this method

  1. We check if there is a twitter account available on the device.
  2. We create a SLComposeViewController object, which embeds the tweet sheet and all functionality.
  3. The initial tweet text is set, also the selected image is added to the tweet.
  4. The tweet sheet is presented.
  5. If the twitter account isn't set up, we display an alert message at the console

Finally, we must implement the imagePickerController:didFinishPickingMediaWithInfo method. Here we assign the chosen image from the library to the image view.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        
    self.dismiss(animated: true, completion: nil)
}

To grant access to the Photo Library an key must be added to the Info.plist file. Open this file select the plus sign and add the following key

Before the project can bar run a Twitter account must be created  in the Settings of the iOS Simulator. 

Build and Run the project. The application will ask for permission to access the Photo Library, which you need to Allow. Next, Press the "Choose Image" button and select a picture from the Photo Library. Next, press the tweet button to create and send the tweet.

You can download the source code of the IOS10TwitterTutorial at the ioscreator repository on github