Search code examples
swiftios10

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.

Research

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

Implementation

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() {
    super.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!!


Solution

  • 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 = contactProperty.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
          ...
       }
    }