Image of contacts is not fetching
Asked Answered
B

2

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.

Bullish answered 19/4, 2017 at 9:51 Comment(5)
I saw this . this doesn't answer my question. :(Bullish
Did you add CNContactImageDataAvailableKey and CNContactImageDataKey on the keys to fetch?Weise
getting same error after adding these.Bullish
I guess you haven't add permission in Info.plist... Add that, and then see if your problem get fixedWeise
Possible duplicate of how to fetch contact image and phone Number in my app using Objective CWeise
C
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")
}
Couture answered 19/4, 2017 at 11:21 Comment(5)
i tried your code it shows "Terminating app due to uncaught exception 'CNPropertyNotFetchedException', reason: 'A property was not requested when contact was fetched.'"Bullish
Please show your fetch request. I assume you did not add CNContactImageDataAvailableKey and/or CNContactThumbnailImageDataKey to your keysToFetch. Updated answer.Couture
i have add these two line now still getting crash . let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey,CNContactImageDataAvailableKey ,CNContactThumbnailImageDataKey] as [Any]Bullish
i forgot to put CNContactImageDataKey. Thanks.Bullish
how to set String(describing: UIImage(data: imageData)) to imageview?Prosector
A
1

Add Keys to your fetch request (image keys missing)

 let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey]
 let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
Acaricide answered 15/3, 2019 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.