Get image from Swift contact

Desired behavior

I am wondering what is the best way to do the following in Swift

  • Display contact selection window
  • Allow user to select contact
  • Get the image from this contact.

Study

When researching this issue, I decided that, starting with iOS 9, Apple introduced a new Contacts structure for accessing contacts. I also found out that Their documentation describes the use of a system called Predicates to receive information from a contact. However, I am not sure how to implement this.

Implementation

Based on this lesson , I figured out how to present the Contact 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!

+6
source share
1 answer

There are three properties associated with contact images according to the API reference document :

Image properties

var imageData: data? Contact profile picture.

var thumbnailImageData: data? Thumbnail version of the contact profile picture.

var imageDataAvailable: Bool Indicates whether the contact has a profile image.

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

So your code might 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 ... } } 
+7
source

All Articles