Upgrade to Pro — share decks privately, control downloads, hide ads and more …

iOS 8 App Extensions

iOS 8 App Extensions

A presentation originally delivered at Pragma Mark in Milan, Italy on October 4th, 2014,

Ben Scheirman

October 03, 2014
Tweet

More Decks by Ben Scheirman

Other Decks in Programming

Transcript

  1. Extensions in
    iOS 8
    (like peanut butter and chocolate)

    View Slide

  2. Ben Scheirman
    @subdigital
    benscheirman.com

    View Slide

  3. ChaiOne
    Houston, TX
    @chaione

    View Slide

  4. NSScreencast

    View Slide

  5. Extensions!

    View Slide

  6. Your App + Other Apps

    View Slide

  7. Your App + 's Apps

    View Slide

  8. Extension Types Available

    View Slide

  9. Today Extension
    Add Widget to Notification
    Center

    View Slide

  10. Share Extension
    Share Content to Your App

    View Slide

  11. Action Extension
    Act Upon Content

    View Slide

  12. Keyboard
    Photo Editing
    Document Provider
    Not covered here :(

    View Slide

  13. Extension
    Architecture

    View Slide

  14. Isolated Process

    View Slide

  15. Independent Lifecycle

    View Slide

  16. Delivered with
    Applications

    View Slide

  17. View Slide

  18. View Slide

  19. Extensions are Just View
    Controllers

    View Slide

  20. The Ever-Important Info.plist

    View Slide

  21. NSExtension
    top level dictionary

    View Slide

  22. NSExtensionAttributes
    nested dictionary

    View Slide

  23. NSExtensionPrincipalClassName
    Provide a class to instantiate if not using
    storyboards.

    View Slide

  24. NSExtensionMainStoryboard
    Provide the name of your extension's storyboard.

    View Slide

  25. NSExtensionPointIdentifier
    Indicates the type of extension to the OS.

    View Slide

  26. What is an Activation Rule?

    View Slide

  27. Supported Activation Rules
    NSExtensionActivationSupportsAttachmentsWithMaxCount
    NSExtensionActivationSupportsAttachmentsWithMinCount
    NSExtensionActivationSupportsFileWithMaxCount
    NSExtensionActivationSupportsImageWithMaxCount
    NSExtensionActivationSupportsMovieWithMaxCount
    NSExtensionActivationSupportsText
    NSExtensionActivationSupportsWebURLWithMaxCount
    NSExtensionActivationSupportsWebPageWithMaxCount

    View Slide

  28. or a Predicate

    View Slide

  29. Default is TRUEPREDICATE

    View Slide

  30. Don't Ship with this!

    View Slide

  31. SUBQUERY (
    extensionItems,
    $extensionItem,
    SUBQUERY (
    $extensionItem.attachments,
    $attachment,
    ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "com.adobe.pdf"
    ).@count == $extensionItem.attachments.@count
    ).@count == 1

    View Slide

  32. Info.plist
    Lots more options, read:
    https://developer.apple.com/library/prerelease/
    iOS/documentation/General/Reference/
    InfoPlistKeyReference/Articles/
    SystemExtensionKeys.html

    View Slide

  33. Sharing Code Between App
    and Extensions

    View Slide

  34. Easy way:
    just add a class to multiple targets!

    View Slide

  35. View Slide

  36. Though, you probably want to create a
    Framework

    View Slide

  37. View Slide

  38. View Slide

  39. Sharing Storyboards?

    View Slide

  40. Let's build a today extension

    View Slide

  41. Step 1: Add Extension
    Target

    View Slide

  42. View Slide

  43. Step 2: Design the Widget

    View Slide

  44. View Slide

  45. Step 3: Share Common
    Code

    View Slide

  46. View Slide

  47. Step 4: Wire it up

    View Slide

  48. View Slide

  49. Let's see
    it in action!

    View Slide

  50. View Slide

  51. How do I keep them in sync?

    View Slide

  52. Sharing Data between
    App and Extension

    View Slide

  53. Can Share:
    · NSUserDefaults
    · CoreData
    · Files
    · Background Transfer Sessions

    View Slide

  54. Create an App Group
    must start with "group."

    View Slide

  55. Create for containing app
    Create same group for extension

    View Slide

  56. View Slide

  57. Setup Shared NSUserDefaults
    var userDefaults: NSUserDefaults {
    get {
    return NSUserDefaults(suiteName: "group.com.nsscreencast.coffeetracker")
    }
    }

    View Slide

  58. Add to CoffeeTracker
    var numberOfCups: Int {
    get {
    return userDefaults.integerForKey("cups")
    }
    set {
    userDefaults.setInteger(newValue, forKey: "cups")
    updateDisplay()
    }
    }

    View Slide

  59. Handle Periodic Background Updates
    func widgetPerformUpdateWithCompletionHandler(completionHandler: (NCUpdateResult) -> ()) {
    coffeeTracker.updateDisplay()
    // If an error is encountered, use NCUpdateResult.Failed
    // If there's no update required, use NCUpdateResult.NoData
    // If there's an update, use NCUpdateResult.NewData
    completionHandler(NCUpdateResult.NewData)
    }

    View Slide

  60. Share Extensions

    View Slide

  61. · Share content to another app / service
    · Use System Sharing UI or Custom
    · Upload using shared background session

    View Slide

  62. Introducing... FoodBook

    View Slide

  63. Step 1:
    Add a framework for our
    shared code

    View Slide

  64. View Slide

  65. Useful for putting networking code or
    view controllers common to app and
    extension

    View Slide

  66. Step 2:
    Add a Share Extension
    Target

    View Slide

  67. View Slide

  68. Step 3:
    Update Info.plist

    View Slide

  69. View Slide

  70. View Slide

  71. Step 4:
    Edit View Controller

    View Slide

  72. (brace yourself)

    View Slide

  73. Import MobileCoreServices
    import MobileCoreServices

    View Slide

  74. Add a property to store the image being shared
    var image: UIImage?

    View Slide

  75. Get the Item Provider
    override func viewDidLoad() {
    var itemProvider: NSItemProvider?
    }

    View Slide

  76. Get the Item Provider
    override func viewDidLoad() {
    var itemProvider: NSItemProvider?
    if let items = extensionContext?.inputItems {
    }
    }

    View Slide

  77. Get the Item Provider
    override func viewDidLoad() {
    var itemProvider: NSItemProvider?
    if let items = extensionContext?.inputItems {
    if let item = items.first
    as? NSExtensionItem {
    }
    }
    }

    View Slide

  78. Get the Item Provider
    override func viewDidLoad() {
    var itemProvider: NSItemProvider?
    if let items = extensionContext?.inputItems {
    if let item = items.first
    as? NSExtensionItem {
    if let attachment = item.attachments?.first
    as? NSItemProvider {
    itemProvider = attachment
    }
    }
    }
    }

    View Slide

  79. Pull an image out of the item provider
    override func viewDidLoad() {
    // ...
    let imageType = kUTTypeImage as NSString
    if itemProvider?.hasItemConformingToTypeIdentifier(imageType) == true {
    }
    }

    View Slide

  80. Pull an image out of the item provider
    override func viewDidLoad() {
    // ...
    let imageType = kUTTypeImage as NSString
    if itemProvider?.hasItemConformingToTypeIdentifier(imageType) == true {
    itemProvider?.loadItemForTypeIdentifier(imageType, options: nil) {
    (item, error) in
    })
    }
    }

    View Slide

  81. Pull an image out of the item provider
    override func viewDidLoad() {
    // ...
    let imageType = kUTTypeImage as NSString
    if itemProvider?.hasItemConformingToTypeIdentifier(imageType) == true {
    itemProvider?.loadItemForTypeIdentifier(imageType, options: nil) {
    (item, error) in
    if error == nil {
    let url = item as NSURL
    let imageData = NSData(contentsOfURL: url)
    self.image = UIImage(data: imageData)
    } else {
    println("ERROR: \(error)")
    }
    })
    }
    }

    View Slide

  82. Step 5: Perform the upload

    View Slide

  83. override func didSelectPost() {
    FoodBookApiClient.upload(image) {
    self.extensionContext!.completeRequestReturningItems([],
    completionHandler: nil)
    }
    }

    View Slide

  84. Let's see
    it in action!

    View Slide

  85. View Slide

  86. Can also bring your own
    view controller

    View Slide

  87. Action Extensions

    View Slide

  88. Act upon content user is looking at

    View Slide

  89. View Slide

  90. Access to Entire DOM

    View Slide

  91. Supply JavaScript that formats the input and
    handles the output

    View Slide

  92. View Slide

  93. Action.js
    var Action = function() {};
    Action.prototype = {
    run: function(arguments) {
    },
    finalize: function(arguments) {
    }
    };
    var ExtensionPreprocessingJS = new Action

    View Slide

  94. run: function(arguments) {
    arguments.completionFunction({
    "host": window.location.host,
    "path": window.location.pathname
    })
    },

    View Slide

  95. App will receive
    PropertyList Item Type

    View Slide

  96. func beginRequestWithExtensionContext(context: NSExtensionContext) {
    self.extensionContext = context
    var itemProvider: NSItemProvider?
    if let item = context.inputItems.first as? NSExtensionItem {
    if let attachment = item.attachments?.first as? NSItemProvider {
    itemProvider = attachment
    }
    }
    let itemType = String(kUTTypePropertyList)
    if itemProvider?.hasItemConformingToTypeIdentifier(itemType) == true {
    itemProvider?.loadItemForTypeIdentifier(itemType, options: nil) {
    item, error in
    let dictionary = item as NSDictionary
    NSOperationQueue.mainQueue().addOperationWithBlock {
    let preprocessingResults = dictionary[NSExtensionJavaScriptPreprocessingResultsKey]
    as [NSObject:AnyObject]
    self.itemLoadCompletedWithPreprocessingResults(preprocessingResults)
    }
    }
    } else {
    self.doneWithResults(nil)
    }
    }

    View Slide

  97. let dictionary = item as NSDictionary
    NSOperationQueue.mainQueue().addOperationWithBlock {
    let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey]
    as NSDictionary
    self.itemLoadCompletedWithPreprocessingResults(results)

    View Slide

  98. func itemLoadCompletedWithPreprocessingResults(results: NSDictionary) {
    let host = results["host"] as String
    let path = results["path"] as String
    let newURL = "http://cat.\(host).meowbify.com\(path)"
    doneWithResults(["newURL": newURL])
    }

    View Slide

  99. Prepare the results to go back to
    the JavaScript object

    View Slide

  100. func doneWithResults(results: NSDictionary?) {
    if let finalizeResults = results {
    var resultsDictionary = [NSExtensionJavaScriptFinalizeArgumentKey: finalizeResults]
    let itemType = kUTTypePropertyList as NSString
    var resultsProvider = NSItemProvider(item: resultsDictionary, typeIdentifier: itemType)
    var resultsItem = NSExtensionItem()
    resultsItem.attachments = [resultsProvider]
    extensionContext?.completeRequestReturningItems([resultsItem], completionHandler: nil)
    } else {
    extensionContext?.completeRequestReturningItems(nil, completionHandler: nil)
    }
    extensionContext = nil
    }

    View Slide

  101. Handle the results in JavaScript

    View Slide

  102. finalize: function(arguments) {
    window.location = arguments["newURL"];
    }

    View Slide

  103. OMG, can we run it yet?

    View Slide

  104. View Slide

  105. Questions?

    View Slide

  106. Thank you!
    Slide links: http://speakerdeck.com/subdigital/ios8-app-extension
    Code links: https://github.com/subdigital/pragma-mark-2014
    Ben Scheirman
    [email protected]
    @subdigital
    @nsscreencast

    View Slide