5

I am using this code to fetch contact image from device but its not printing any output.

if contact.isKeyAvailable(CNContactImageDataKey) {
    if let contactImageData = contact.thumbnailImageData {
        print("image \(String(describing: UIImage(data: contactImageData)))")
    } else {
        print("No image available")
    }
} else {
    print("No Key image available")
}

but it is printing only "No Key image available" though some of my contacts have images . i tried imageData instead of thumbnailImageData but showing same results.

haider_kazal
  • 3,448
  • 2
  • 20
  • 42
Mitu Vinci
  • 455
  • 9
  • 21

2 Answers2

8

Make sure CNContactImageDataAvailableKey and CNContactThumbnailImageDataKey is contained in your keysToFetch and remove the isKeyAvailable if clause:

if let imageData = contact.thumbnailImageData {
    print("image \(String(describing: UIImage(data: imageData)))")
} else {
    print("No image available")
}
shallowThought
  • 19,212
  • 9
  • 65
  • 112
  • i tried your code it shows "Terminating app due to uncaught exception 'CNPropertyNotFetchedException', reason: 'A property was not requested when contact was fetched.'" – Mitu Vinci Apr 19 '17 at 11:47
  • 1
    Please show your fetch request. I assume you did not add `CNContactImageDataAvailableKey` and/or `CNContactThumbnailImageDataKey` to your `keysToFetch`. Updated answer. – shallowThought Apr 19 '17 at 11:53
  • i have add these two line now still getting crash . let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey,CNContactImageDataAvailableKey ,CNContactThumbnailImageDataKey] as [Any] – Mitu Vinci Apr 19 '17 at 12:34
  • i forgot to put CNContactImageDataKey. Thanks. – Mitu Vinci Apr 19 '17 at 12:41
  • how to set ```String(describing: UIImage(data: imageData))``` to imageview? – Arjun Feb 01 '22 at 11:51
1

Add Keys to your fetch request (image keys missing)

 let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey]
 let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
user3826696
  • 1,045
  • 12
  • 13