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 SMS, and more. In this tutorial, an image will be saved to the Photo Library in the simulator. This tutorial is made with Xcode 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11ActivityViewControllerTutorial 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 Assetts 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 Button and select the Auto Layout Align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Image View and select the Auto Layout "Add New Contraints" button. Pin the Button to the top. Select the Width and Height constraints and and click "Add 3 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() {
    super.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.

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