---
title: "iOS 9 bites - Little Bites of Cocoa"
description: "Little Bites of Cocoa about iOS 9: short tips and techniques for iOS and Mac development, each a brief explanation of one concept, technique or tool."
url: "https://littlebitesofcocoa.com/topics/2-ios-9"
author: "Jake Marsh"
---
# Bites about: [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)
- [Layout](https://littlebitesofcocoa.com/topics/3-layout)

## [#103: UIStackView in Code 🚥📐](https://littlebitesofcocoa.com/103-uistackview-in-code)

 Wednesday October 14th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)
- [Layout](https://littlebitesofcocoa.com/topics/3-layout)

We covered *UIStackView* when it was first announced, way back in [Bite #16](https://littlebitesofcocoa.com/16-uistackview). Today we'll look at how to use it in code to build a **section header view**:

![Image 1 of 5 from bite #103: UIStackView in Code](https://media.littlebitesofcocoa.com/bite-assets/103-uistackview-in-code-1-preview.png)

We'll be stacking 3 regular views: a **UIImageView**, then a **UILabel**, and finally a **UIButton**

Nothing special about them besides fonts/colors, so we've created them off camera.

Here's our first attempt:

```swift
stackView = UIStackView(arrangedSubviews: [imageView, label, button])

stackView.axis = .Horizontal
stackView.translatesAutoresizingMaskIntoConstraints = false

addSubview(stackView)

addConstraintsWithVFL("|[stackView]|")
addConstraintsWithVFL("V:|[stackView]|")
```

Like in [Bite #99](https://littlebitesofcocoa.com/99-auto-layout-visual-format-language), we'll use **Auto Layout Visual Format Language** to pin the *stack view's* edges to its **superview**. Look at that, not bad for our first try!

![Image 2 of 5 from bite #103: UIStackView in Code](https://media.littlebitesofcocoa.com/bite-assets/103-uistackview-in-code-2-first-try.png)

Those **views** are [close talkers](https://www.youtube.com/watch?v=NGVSIkEi3mM), let's add some spacing:

```swift
stackView.spacing = 10.0
```

![Image 3 of 5 from bite #103: UIStackView in Code](https://media.littlebitesofcocoa.com/bite-assets/103-uistackview-in-code-3-with-spacing.png)

Ack! What the heck is going on here?!

Let's break it down: In the default ‘Fill' distribution mode, if **views** don't naturally fill the axis of the *stack view*, the *stack view* will resize one (or more) according to their **hugging priority** (covered in [Bite #69](https://littlebitesofcocoa.com/69-compression-resistance-content-hugging)).

We'll solve our issue by setting a low **hugging priority** on our **label**, signaling to the *stack view* that *it* be the one to stretch, not our **image view**.

```swift
titleLabel.setContentHuggingPriority(1, forAxis: .Horizontal)
```

![Image 4 of 5 from bite #103: UIStackView in Code](https://media.littlebitesofcocoa.com/bite-assets/103-uistackview-in-code-4-fixed-stretch.png)

Nice, much room-ier! Finally, let's use one more trick to make the *stack view* add some padding around its edges:

```swift
stackView.layoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsetsMake(7.0, 7.0, 7.0, 7.0)
```

![Image 5 of 5 from bite #103: UIStackView in Code](https://media.littlebitesofcocoa.com/bite-assets/103-uistackview-in-code-5-final.png)

Success, matches our design perfectly! **Download the project** at [j.mp/bite103](http://j.mp/bite103)

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Extensions](https://littlebitesofcocoa.com/topics/17-extensions)

## [#92: Shared Links Extensions 📰🔗](https://littlebitesofcocoa.com/92-shared-links-extensions)

 Tuesday September 29th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Extensions](https://littlebitesofcocoa.com/topics/17-extensions)

*Shared Links Extensions* arrived with **iOS 9** and **OS X El Capitan** this year. They allow our **app** to insert content into the users' **Shared Links** section of **Safari** on **iOS** or **OS X**. Let's add one to our fictional *Little Bites of Cocoa* **app** so users can see all the latest **Bites** right inside **Shared Links**.

We'll start by going to **File** > **New** > **Target...** in **Xcode** and choosing a *Shared Links Extension*.

![Image 1 of 3 from bite #92: Shared Links Extensions](https://media.littlebitesofcocoa.com/bite-assets/092-shared-links-extensions-target.png)

This will provide us with a new **group** in our **project** with one **file** inside, called **RequestHandler.swift**.

In this **file** there's one **function** called `beginRequestWithExtensionContext(context:)`.

**iOS** will call this on our **extension** and that will be our cue to run whatever code we need to load the content we'd like to show in **Shared Links**, then return it in the form of an **array** of **NSExtensionItems**.

We'll return them via a completion **function** on the **context** we're passed in.

```swift
class RequestHandler: NSObject, NSExtensionRequestHandling {
  func beginRequestWithExtensionContext(context: NSExtensionContext) {
    Bite.loadNewest { bites in
      let extensionItems = bites.map { bite -> NSExtensionItem in
        let item = NSExtensionItem()

        item.userInfo = [
          "uniqueIdentifier": "lboc-bite-\(bite.number!)",
          "urlString": "https://littlebitesofcocoa.com/\(bite.number!)",
          "date": bite.publishedAt
        ]

        item.attributedTitle = NSAttributedString(string: bite.title)
        item.attributedContentText = bite.content
        item.attachments = [
          NSItemProvider(contentsOfURL: bite.imageURL())!
        ]

        return item
      }

      context.completeRequestReturningItems(extensionItems,
        completionHandler: nil)
    }
  }
}
```

Lastly, we'll install our **app**, then head to **Shared Links** in **Safari**. We'll enable our **extension** under **Subscriptions**.

![Image 2 of 3 from bite #92: Shared Links Extensions](https://media.littlebitesofcocoa.com/bite-assets/092-shared-links-extensions-enable.png)

Success!

![Image 3 of 3 from bite #92: Shared Links Extensions](https://media.littlebitesofcocoa.com/bite-assets/092-shared-links-extensions-success.png)

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)

## [#91: Universal Links 🌎🔗](https://littlebitesofcocoa.com/91-universal-links)

 Monday September 28th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)

*Universal Links* arrived with **iOS 9**. Conceptually they're a way for us to logically tie the content in our **app** to the content on our **website**. Once this is done, **iOS** will be able to launch our **app** when a user taps a link somewhere, rather than opening our site in **Safari**. Let's take a further look by adding *Universal Links* to a fictional *Little Bites of Cocoa* **app**. We'll start by registering and setting up **SSL** for our domain: *littlebitesofcocoa.com*.

Then, we'll head into **Xcode** and to the **Capabilities tab** of our **project**. We'll flip on the switch for **Associated Domains**, then click the **+ button** and add our **domain**. Note that we prefix it with the phrase `applinks:`.

![Image from bite #91: Universal Links](https://media.littlebitesofcocoa.com/bite-assets/091-universal-links-associated-domains.png)

Now, our **app** will silently make an **HTTP GET** request to
`https://littlebitesofcocoa.com/apple-app-site-association`.

It will expect us to return some **JSON** which describes our **app's Bundle ID**, and which **paths** should open it.

We'll open all **paths** on our **domain** using a **wildcard character** here, but we could easily, for example, limit to just *Bite* URLs.

```json
{
  "applinks": {
    "apps": [],
    "details": {
      "TEAMIDHERE.com.magnus.lboc": {
        "paths": [ "*" ]
      }
    }
  }
}
```

After creating the **file**, we'll need to **sign** it so it is returned with a **Content-Type** of **application/pkcs7-mime** on our server. We'll use a **command** like the one shown here to **sign** the **file**. (This part stinks, but there's no way around it).

```shell
cat aasa.json | openssl smime -sign
                              -inkey littlebitesofcocoa.com.key
                              -signer littlebitesofcocoa.com.pem
                              -certfile intermediate.pem
                              -noattr
                              -nodetach
                              -outform DER > apple-app-site-association
```

Lastly, we'll wire up the other side of the equation. When a user opens a *Universal Link* that **iOS** recognizes, it will call the same **delegate function** that's used to implement features like **Handoff** ([Bite #29](https://littlebitesofcocoa.com/29-handoff)) and **Spotlight Search** ([Bite #23](https://littlebitesofcocoa.com/23-core-spotlight)). We'll check if it's a **Universal Links** activity type, then use **JLRoutes** ([Bite #62](https://littlebitesofcocoa.com/62-jlroutes)) to open a section of our app.

```swift
extension AppDelegate {
  func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {

    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
      return JLRoutes.routeURL(userActivity.webpageURL!)
    }

    return true
  }
}
```

Topics

- [Tools](https://littlebitesofcocoa.com/topics/9-tools)
- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Testing](https://littlebitesofcocoa.com/topics/58-testing)

## [#30: UI Testing 🚸](https://littlebitesofcocoa.com/30-ui-testing)

 Friday July 3rd, 2015

Topics

- [Tools](https://littlebitesofcocoa.com/topics/9-tools)
- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Testing](https://littlebitesofcocoa.com/topics/58-testing)

Testing is incredibly important in ensuring our app arrives to our users in as good a state as possible.

Xcode has had great unit testing support for a few releases now, but testing our UI has always been a challenge.

Instruments added support for it a while back, but it’s never felt like a first class citizen... Until now!

Xcode 7 brings us an awesome, fully baked set of UI testing tools. We can even make Xcode write much of your test code for us by simply interacting with our app.

Here's an example test created using the default Master-Detail template in Xcode. It presses the add button 3 times, then verifies that 3 cells now exist in the table view:

```swift
func testExample() {
    let app = XCUIApplication()

    let masterNavigationBar = app.navigationBars["Master"]
    let addButton = masterNavigationBar.buttons["Add"]

    addButton.tap()
    addButton.tap()
    addButton.tap()

    XCTAssert(app.tables.childrenMatchingType(.Cell).count == 3)
}
```

![Image 1 of 2 from bite #30: UI Testing](https://media.littlebitesofcocoa.com/bite-assets/030-ui-testing-record-screenshot.png)

Recording UI Tests couldn't be easier. We just write an new empty test function, put our cursor in the middle of it, and press record.

![Image 2 of 2 from bite #30: UI Testing](https://media.littlebitesofcocoa.com/bite-assets/030-ui-testing-accessibility.png)

UI Testing uses Accessibility under the hood to identify and retrieve UI elements at runtime. Just one more reason to make our apps as accessible as possible!

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Media](https://littlebitesofcocoa.com/topics/38-media)

## [#25: Picture in Picture 📺](https://littlebitesofcocoa.com/25-picture-in-picture)

 Friday June 26th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Media](https://littlebitesofcocoa.com/topics/38-media)

One of the coolest new features in **iOS 9** is the new **Picture in Picture** functionality on **iPad**. This lets users watch video content from an app even while it's in the background.

To support it in our app, we'll first make sure you set the `Playback` audio category in our `application(application:didFinishLaunchingWithOptions:)` function:

```swift
do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch { }
```

Then we'll use `AVPlayerViewController` to play video content. **Picture in Picture** mode will automatically kick-in if our app enters background but only if: 1.) our player is full screen, 2.) video content is playing in it, *and* 3.) **Picture in Picture** is supported on the device.

Next we'll implement this wonderfully long delegate method to restore our player UI when the user returns from **Picture in Picture** mode:

```swift
func playerViewController(playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: (Bool) -> Void) {
  navigationController?.presentViewController(playerViewController, animated: true) {
    completionHandler(true)
  }
}
```

## More About PIP

- If we need to support a generic `AVPlayerLayer`, **AVKit** also includes a new `AVPictureInPictureController`.
- We also get **PIP** for free in `WKWebView` assuming our app has the `Playback` audio session category set.

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Contacts](https://littlebitesofcocoa.com/topics/39-contacts)

## [#24: Contacts and Contacts UI 👥](https://littlebitesofcocoa.com/24-contacts-and-contacts-ui)

 Thursday June 25th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Contacts](https://littlebitesofcocoa.com/topics/39-contacts)

Interacting with a user's Contacts database used to be, shall we say, "less than ideal". The **AddressBook** framework was great for it’s time, but it’s a bit past it's prime these days.

**Contacts** and **Contacts UI** are two new frameworks in **iOS 9** (and **OS X** + **watchOS**) that make integrating Contact data into your app a breeze.

Here's how easy it is to search a user’s contacts and present one for viewing:

```swift
func presentContactMatchingName(name: String) throws {
    let predicate = CNContact.predicateForContactsMatchingName(name)
    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey]
    let store = CNContactStore()

    let contacts = try store.unifiedContactsMatchingPredicate(
        predicate,
        keysToFetch: keysToFetch
    )

    if let firstContact = contacts.first {
        let viewController = CNContactViewController(forContact: firstContact)
        viewController.contactStore = self.store

        presentViewController(viewController, animated: true, completion: nil)
    }
}
```

Also, Apple has officially deprecated **AddressBook** and **AddressBookUI** so now's the time to make the switch!

![Image from bite #24: Contacts and Contacts UI](https://media.littlebitesofcocoa.com/bite-assets/024-contacts-contacts-ui-example.png)

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Core Spotlight](https://littlebitesofcocoa.com/topics/40-core-spotlight)

## [#23: Core Spotlight 🔍](https://littlebitesofcocoa.com/23-core-spotlight)

 Wednesday June 24th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Core Spotlight](https://littlebitesofcocoa.com/topics/40-core-spotlight)

**[Core Spotlight](https://developer.apple.com/library/prerelease/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS9.html)** allows your content to appear in the results of system-level Spotlight searches.

```swift
let attrSet = CSSearchableItemAttributeSet(
  itemContentType: kUTTypeText as String
)

attrSet.title = "#23: CoreSpotlight"
attrSet.contentDescription = "CoreSpotlight allows your content to appear in the results of system-level Spotlight searches."

let item = CSSearchableItem(
  uniqueIdentifier: "023",
  domainIdentifier: "com.lilbitesofcocoa.bites",
  attributeSet: attrSet
)

CSSearchableIndex
  .defaultSearchableIndex()
  .indexSearchableItems([item]) { error in
    print("Success!")
  }
```

![Image from bite #23: Core Spotlight](https://media.littlebitesofcocoa.com/bite-assets/023-corespotlight-example.png)

Of course **Core Spotlight** is just one of many ways to get your content into search results, be sure to also look into the [NSUserActivity APIs](https://developer.apple.com/library/prerelease/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS9.html#//apple_ref/doc/uid/TP40016198-SW2) as well as [Apple's Web markup guides](https://developer.apple.com/library/prerelease/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS9.html#//apple_ref/doc/uid/TP40016198-SW4).

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [ReplayKit](https://littlebitesofcocoa.com/topics/42-replaykit)

## [#20: ReplayKit 🎥](https://littlebitesofcocoa.com/20-replaykit)

 Friday June 19th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [ReplayKit](https://littlebitesofcocoa.com/topics/42-replaykit)

**ReplayKit** in **iOS 9** allows you to record a movie of what's happening on screen in your app or game. Here's a quick example of how to use it:

```swift
import ReplayKit

class GameViewController: UIViewController {
  func startRecording() {
    let recorder = RPScreenRecorder.sharedRecorder()
    recorder.startRecordingWithMicrophoneEnabled(true)
  }

  func stopRecording() {
    let recorder = RPScreenRecorder.sharedRecorder()

    recorder.stopRecordingWithHandler { (previewVC, error) in
      if let vc = previewVC {
        self.presentViewController(
          vc,
          animated: true,
          completion: nil
        )
      }
    }
  }
}
```

![Image from bite #20: ReplayKit](https://media.littlebitesofcocoa.com/bite-assets/020-replaykit-things-to-know.png)

- Records app audio, optionally also records microphone audio. The user is given the chance to preview and, edit , and trim the video before exporting.
- You can't access the movie file itself. After recording, user is shown an activity view controller, which you can add custom actions to.
- Recording is polite to battery and performance.
- Only works A7 and A8 devices.
- Permission from the user is required to begin recording.
- Recording automatically excludes system UI like notifications or keyboard entry.

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Web](https://littlebitesofcocoa.com/topics/43-web)

## [#18: SFSafariViewController 👒🏄](https://littlebitesofcocoa.com/18-sfsafariviewcontroller)

 Wednesday June 17th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [Web](https://littlebitesofcocoa.com/topics/43-web)

*SFSafariViewController* is another new addition in iOS 9, and it’s a great one.

Get ready to throw out all that custom in-app browser or third-party library code you’ve been using.

Unlike other solutions, *SFSafariViewController* embeds all of the power of Safari on iOS (including Autofill, shared cookies, etc.) directly into your app.

Replacing your existing solutions should be trivial for most people, here’s how:

```swift
import SafariServices

class BookmarksViewController : UITableViewController {

  func didSelectBookmark(bookmark: Bookmark) {
    let vc = SFSafariViewController(
      URL: bookmark.URL,
      entersReaderIfAvailable: false
    )

    presentViewController(vc, animated: true, completion: nil)
  }

}
```

![Image from bite #18: SFSafariViewController](https://media.littlebitesofcocoa.com/bite-assets/018-sfsafariviewcontroller-example.png)

## SFSafariViewController Pro Tips

- set a delegate to configure custom activity items in the share sheet
- use the `entersReaderIfAvailable` property to start the user in reader view

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)

## [#17: UIKeyCommand 🔑⌘](https://littlebitesofcocoa.com/17-uikeycommand)

 Tuesday June 16th, 2015

Topics

- [iOS 9](https://littlebitesofcocoa.com/topics/2-ios-9)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)

iOS has had support for hardware keyboard shortcuts for a while now. **New in iOS 9**, Apple has made some great improvements to how apps can take advantage of them. Your app can now register keyboard shortcuts *per view controller*, and all currently valid shortcuts will be neatly
 summarized when the user brings up the new keyboard shortcuts view.

Wiring up a new keyboard shortcut in this system couldn't be easier. Just define a new function, create a new `UIKeyCommand` and then call `addKeyCommand` on your view controller:

```swift
// inside some UIViewController subclass:

override func viewDidLoad() {
  super.viewDidLoad()

  let shortcut = UIKeyCommand(
    input: "n",
    modifierFlags: UIKeyModifierFlags.Command,
    action: "createNewFile:"
  )

  addKeyCommand(shortcut)
}

func createNewFile(command: UIKeyCommand) {
  // do the thing
}
```

![Image 1 of 2 from bite #17: UIKeyCommand](https://media.littlebitesofcocoa.com/bite-assets/017-uikeycommand-shortcuts.png)

![Image 2 of 2 from bite #17: UIKeyCommand](https://media.littlebitesofcocoa.com/bite-assets/017-uikeycommand-app-switching.png)

 

Page 1 of 2

[Next   ](https://littlebitesofcocoa.com/topics/2-ios-9?page=2)
