rocket101 rocket101 - 3 years ago 93
Swift Question

Get image from Contact Swift

Desired Behavior

I am wondering how to best do the following in Swift

  1. Display a contact picker window

  2. Allow a user to select a contact

  3. Fetch an image from that contact.


In researching this question, I have determined that, beginning in iOS 9, Apple introduced a new framework,
, for accessing contacts. I also learned that Their documentation describes using a system called
for fetching information from a contact. However, I am unsure of how to implement this.


Based primarly on this tutorial, I have figured out how to present the Contacts Picker window.

import UIKit
import Contacts
import ContactsUI

class ViewController: UIViewController, CNContactPickerDelegate {

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
@IBAction func contactsPressed(_ sender: AnyObject) {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self;

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

func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
//Here is where I am stuck - how do I get the image from the contact?


Thanks in advance!!

Answer Source

There are three properties related to contact images according to the API reference doc from apple:

Image Properties

var imageData: Data? The profile picture of a contact.

var thumbnailImageData: Data? The thumbnail version of the contact’s profile picture.

var imageDataAvailable: Bool Indicates whether a contact has a profile picture.

You can get the CNContact instance from CNContactProperty, and then access imageData in CNContact class.

So your code may look like this:

func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
   let contact =
   if contact.imageDataAvailable {
      // there is an image for this contact
      let image = UIImage(data: contact.imageData)
      // Do what ever you want with the contact image below
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download