How to Display the iOS Share Sheet using Swift


  • Share on Pinterest

A nice feature on iOS is the ability to share just about anything to anywhere using the built in sharing system. To achieve this in applications you can use the UIActivityViewController. I will show you how in this tutorial.

We have all seen this feature. You find a great piece of content and want to Tweet it, post it to Facebook or maybe just email to a friend. That is when the magic of the sharing sheet appears.

IMG_0360

It is not hard to add this feature to your Swift applications thanks to iOS. You only need to tell iOS what you want to share and it will present only those options capable of handling the content you send to it. It is worth noting that you can override the options iOS gives you but we will not cover that this time around. One thing to remember, on iPhone you present the sheet as a modal view but on the iPad you have to present it as a popover.

We are going to create an iPhone application with a text field to enter some text and a button that shares the contents using share sheet.

Setup

Start by creating a Swift based iOS application in Xcode. Now add a text field and a button using your method of choice. I added them to a storyboard from the object library. Next create an @IBAction and @IBOutlet for each in the view controller. I also added constraints to keep the layout nice and pretty regardless of the device.

Storyboard with Text Field and Button

Code Up the Magic

The button needs to handle any possible out comes and handle them gracefully. The share sheet should only show if there is something to share. We will check if the text field is empty and if it is just alert the user giving them instructions to enter something and try again.

If you are not familiar with the UIAlertController then I recommend my article ‘Display an Alert or Action Sheet Using Swift in iOS 8‘.

We are going to keep the code tidy by separating the creation and display of the Alert in a separate method. We will call the method with a title and message, add the following func to the view controller.

func displayAlert(title: String, message: String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    presentViewController(alertController, animated: true, completion: nil)
    return
}

 

We call the method and tell it what to display. So back in the button @IBOutlet add the following if statement to check the contents of the field and call displayAlert when the field is empty.

@IBAction func myShareButton(sender: UIButton) {
    // Hide the keyboard
    myTextField.resignFirstResponder()
    // Check and see if the text field is empty
    if (myTextField.text == "") {
        // The text field is empty so display an Alert
        displayAlert("Warning", message: "Enter something in the text field!")
    } else {
        // We have contents so display the share sheet
    }
}

 

Now to complete the button code we fill in that empty else statement with our call to the share sheet. To keep the code reusable we call a method to display the share sheet. Add the following method after func displayAlert(title: String, message: String) in the view controller.

func displayShareSheet(shareContent:String) {
    let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
    presentViewController(activityViewController, animated: true, completion: {})
}

 

We start by creating a new instance of the UIActivityViewController class and pass the arguments which in this example is a string. Note that it MUST be cast as an NSString, the UIActivityViewController expects this. Then we display the view.

Our last task is to call this method in the else block. The full code for the button should look something like this.

@IBAction func myShareButton(sender: UIButton) {
    // Hide the keyboard
    myTextField.resignFirstResponder()
    // Check and see if the text field is empty
    if (myTextField.text == "") {
        // The text field is empty so display an Alert
        displayAlert("Warning", message: "Enter something in the text field!")
    } else {
        // We have contents so display the share sheet
        displayShareSheet(myTextField.text!)
    }
}

 

Here is the code for my view controller. You may of used different names for your @IBOutlet and @IBAction and should change as needed.

//
// ViewController.swift
// ShareSheet Example
//
// Created by Peter Witham on 8/22/15.
// Copyright © 2015 Peter Witham. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func myShareButton(sender: UIButton) {
        // Hide the keyboard
        myTextField.resignFirstResponder()
        // Check and see if the text field is empty
        if (myTextField.text == "") {
            // The text field is empty so display an Alert
            displayAlert("Warning", message: "Enter something in the text field!")
        } else {
            // We have contents so display the share sheet
            displayShareSheet(myTextField.text!)
        }
    }

    func displayAlert(title: String, message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
        return
    }

    func displayShareSheet(shareContent:String) {
        let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
        presentViewController(activityViewController, animated: true, completion: {})
    }
}

 

Run the Application

Run the application and enter some text. Click the button and the keyboard should disappear and share sheet should appear. I am using the simulator so share options may be different.

iPhone 6 - Simulator showing text in the text field

iPhone 6 - Simulator showing the share sheet

Wrap Up

This example shows how to start using the share sheet based on the content. I hope it has been useful and if so please share with others. I welcome comments and suggestions on improving the code. I also love to hear how you use this in your applications.

  • Marikins
    Author
    Marikins Marikins

    How would you add Twitter to this?
    Thank you.

    • Peter Witham
      Author
      Peter Witham Peter Witham

      Hi, if there is a twitter account setup on the iOS device then it should be available on the system share sheet, but you may have to add it from the ‘more’ option to the right of the sheet icons.

      I am not aware of a way to force the twitter icon to appear on a users share sheet if that is what you are asking. You could probably go a different route though via the twitter API, but I’m not aware of how to do that.

      • Marikins
        Author
        Marikins Marikins

        Thanks, Peter

        • Peter Witham
          Author
          Peter Witham Peter Witham

          You are most welcome 🙂

  • LiveRowing
    Author
    LiveRowing LiveRowing

    Hi we have a iOS Swift app with native charts & graphs. Could we use this function to share the user charts to social?

    • Peter Witham
      Author
      Peter Witham Peter Witham

      Hi, it uses the standard iOS sharesheet, so you should be able to attach anything you can code up to it for sharing 🙂

      Regards,
      Peter.

      • LiveRowing
        Author
        LiveRowing LiveRowing

        Cool. So even if it’s a native graph or chart? I’m a product guy, not a dev. 😉

        • Peter Witham
          Author
          Peter Witham Peter Witham

          I cannot say for sure since I have not tried it. I am thinking you may have to either attach it as a file or something like that for sending, certainly should be possible once you have the content prepared for sending.

  • Tulakshana Asanka
    Author
    Tulakshana Asanka Tulakshana Asanka

    I noticed that iCloud drive is not visible even if the iCloud app is installed and enabled for my app. Any thoughts on this?

    • Peter Witham
      Author
      Peter Witham Peter Witham

      Interesting, I do not know why. I will have to look in to it.

      • Tulakshana Asanka
        Author
        Tulakshana Asanka Tulakshana Asanka

        Thanks