Activity View Controller iOS Tutorial

The Activity View Controller  is a standard view controller that can be used to offer various services from the application. The system provides several standard services, such as copying items to the pasteboard, posting content to social media sites, sending items via email or iMessage, and more. In this tutorial, an image will be saved to the Photo Library in the simulator. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSActivityViewControllerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

For this tutorial an image is needed. Download the image. Open the Assets folder and drag the downloaded image to it. 

Go to the Storyboard and select the View Controller. Go to the Editor menu and select Embed in -> Navigation Controller

Drag an Image View to the main view. Select the image View and go to the Attribute Inspector. In The Image View section select the image name in the Image field.

Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

The Storyboard should look like this.

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

Change the viewDidLoad method to 

override func viewDidLoad() {
    navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareImage))

A system action button is assigned to the navigation bar. When clicked the shareImage method will be called. Implement this method.

@objc func shareImage() {
    let vc = UIActivityViewController(activityItems: [imageView.image!], applicationActivities: [])
    present(vc, animated: true)

An Activity View Controlller is created and presented with the image view as an acitvity item. The image will be saved to the Photo Library so the user must be granted the permission to access the Photo Library. Open the Info.plist and add a new row. Select "Privacy - Photo Library Additions Usage Description" and fill in a custom text in the adjacent String filed.

Build and Run the project. Select the Action button in the Navigation bar to display the Activitiy View.

Select "Save Image" and Choose OK to grant the application access to the Photo Library. The photo will be added to the Photo Library.

You can download the source code of the IOSActivityViewControllerTutorial at the ioscreator repository on Github.