Receiving Data from an iOS 10 Action Extension

From Techotopia
Jump to: navigation, search

PreviousTable of ContentsNext
Creating an iOS 10 Action ExtensionAn Introduction to Building iOS 10 iMessage Apps


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


The previous chapter covered the steps involved in creating an Action extension in iOS 10 that was designed to modify and display text content from a host app. In developing the extension, steps were taken to ensure that the modified content was returned to the host app when the user exited the extension. This chapter will work through the creation of an example host application that demonstrates how to receive data from an Action extension.




Creating the Example Project

Start Xcode and create a new Single View Application project named ActionHostApp with Swift selected as the programming language and the Devices menu set to Universal. The finished application is going to consist of a Text View object and a toolbar containing a Share button that will provide access to the Change it Up Action extension created in the previous chapter. When the Action extension returns, the host app will receive the modified content from the extension and display it to the user.

Designing the User Interface

Locate and load the Main.storyboard file into the Interface Builder tool and drag and drop a Toolbar instance so that it is positioned along the bottom edge of the layout canvas. Next, drag and drop a Text View object onto the canvas and resize and position it so that it occupies the remaining space above the toolbar, stretching the view out horizontally until the blue margin guidelines appear. With the TextView object selected, display the Attributes Inspector and change the displayed text to “This is some sample text”.

Finally, hold down the keyboard Shift key and click on both the Text View and Toolbar views in the layout. Once both are selected, display the Resolve Auto Layout Issues menu and select the Reset to Suggested Constraints option. At this point the layout should resemble Figure 87-1:


Xcode 8 ios 10 action ext host ui.png

Figure 87-1


Before proceeding, display the Assistant Editor panel and establish an outlet for the Text View object named myTextView.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


Importing the Mobile Core Services Framework

The code added to this project will make use of a definition which is declared within the Mobile Core Services framework. To avoid compilation errors, this framework must be imported into the ViewController.swift file as follows:

import UIKit
import MobileCoreServices

class ViewController: UIViewController {
.
.
.
}

Adding an Action Button to the Application

In order to be able to access the “Change it Up” Action extension from within this host application it will be necessary to implement an Action button. As the user interface currently stands, the toolbar contains a single button item displaying text which reads “Item”. To change this to an Action button, select it in the storyboard layout (keeping in mind that it may be necessary to click on it twice since the first click typically selects the parent toolbar rather than the button item).

With the button selected, display the Attributes Inspector and change the System Item menu from Custom to Action:


Xcode 7 button item action.png

Figure 87-2


Once the change has been made, the button item should now have the standard appearance of an iOS Action button as shown in Figure 87-3:


Ios 8 share button.png

Figure 87-3


Now that the button looks like an Action button, some code needs to be added to display the activity view controller when it is tapped by the user. With the Assistant Editor displayed, Ctrl-click on the button and drag the resulting line to a suitable location within the ViewController.swift file. Release the line and create an Action outlet named showActionView. Once created, implement the code in this method so that it reads as follows:

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

@IBAction func showActionView(_ sender: AnyObject) {
    let activityViewController =
        UIActivityViewController(activityItems:
            [myTextView.text], applicationActivities: nil)

    self.present(activityViewController,
                 animated:true, completion: nil)

    activityViewController.completionWithItemsHandler =
        { (activityType, completed, returnedItems, error) in

        }
} 			

The code within the method creates a new UIActivityViewController instance initialized with the content of the Text View in the user interface. The activity view controller is then displayed to the user. Finally, a closure is assigned to act as the completion handler (the code for which will be implemented later) to be executed when the Action extension returns control to the application.

Compile and run the application and tap the Action button to test that the activity view controller appears. Select the “Change it Up” extension and verify that it displays the text extracted from the Text View. Finally, tap the Done button to return to the host app, noting that the original text content has not yet been converted to uppercase. This functionality now needs to be implemented within the completion handler method.

Receiving Data from an Extension

When the user exits from an Action extension, the completion handler assigned to the UIActivityViewController instance will be called and passed a variety of parameters. One of those parameters will be an array of NSExtensionItem objects containing NSItemProvider objects that can be used to load any data that has been returned by the extension.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Using the same techniques described in the previous chapter (Creating an iOS 10 Action Extension) this data can be extracted by making the following changes to the completion handler closure:

.
.
.
activityViewController.completionWithItemsHandler =
                { (activityType, completed, returnedItems, error) in

           if returnedItems!.count > 0 {

            let textItem: NSExtensionItem =
                returnedItems![0] as! NSExtensionItem


            let textItemProvider =
                textItem.attachments![0] as! NSItemProvider

            if textItemProvider.hasItemConformingToTypeIdentifier(
                kUTTypeText as String) {

                textItemProvider.loadItem(
                    forTypeIdentifier: kUTTypeText as String,
                    options: nil,
                    completionHandler: {(string, error) -> Void in
                        let newtext = string as! String
                        self.myTextView.text = newtext
                })
            }
        }     
    }
}
.
.
.

The method obtains a reference to the item provider and verifies that at least one item has been returned from the extension. A test is then performed to make sure that it is a text item. If the item is text based, the item is loaded from the extension and a completion handler used to assign the new text to the Text View object.

Testing the Application

Compile and run the application, select the Share button and launch the “Change it Up” extension. On returning to the host application the original text should now have been updated to be displayed in uppercase as modified within the extension.

Summary

In addition to providing an alternative view of the content in a host app, Action extensions can also be used to transform that content in some way. Not only can this transformation be performed and viewed within the extension, but a mechanism is also provided to return that modified content to the host app. By default, most host apps will not make use of the returned content. In reality adding this support is a relatively simple task which involves implementing a completion handler method to handle the content returned from the extension into the host app and assigning that handler method to be called when the activity view controller is displayed to the user.


Purchase the fully updated iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
Creating an iOS 8 Action ExtensionAn Introduction to Building iOS 10 iMessage Apps