Reputation: 333
I'm trying to fetch the image property of a given contact
. Here's what I got:
Model
struct Contact: Identifiable {
let contact: CNContact
var id: String { contact.identifier }
var image: Data? { contact.imageData }
var givenName: String { contact.givenName }
}
static func fetch(_ completion: @escaping(Result<[Contact], Error>) -> Void) {
let containerID = CNContactStore().defaultContainerIdentifier
let predicate = CNContact.predicateForContactsInContainer(withIdentifier: containerID())
let keysToFetch = [
CNContactImageDataKey,
CNContactImageDataAvailableKey,
CNContactThumbnailImageDataKey,
CNContactGivenNameKey,
CNContactFamilyNameKey,
CNContactPhoneNumbersKey,
CNContactEmailAddressesKey
] as [CNKeyDescriptor]
do {
let contacts = try CNContactStore().unifiedContacts(matching: predicate, keysToFetch: keysToFetch)
completion(.success(contacts.map({ .init(contact: $0)})))
} catch {
completion(.failure(error))
}
}
View
struct ContactRow: View {
let contact: Contact
var body: some View {
VStack {
HStack {
Image(String(describing: contact.image))
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 50, height: 50)
.background(AppColor())
.clipShape(Circle())
.shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
.shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
Text(contact.givenName)
.font(.headline)
.foregroundColor(Color(#colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)))
}
}
}
}
The error(s) I get are purple, and say
runtime: SwiftUI: No image named 'Optional(38321 bytes)' found in asset catalog for /private/var/containers/Bundle/Application/ ...etc
Obviously I have contact images in my Contacts
app Apple provides.
Any ideas?
Upvotes: 3
Views: 991
Reputation: 258413
Your contact image is Data
, so you should create Image
in different way, like
Image(uiImage: UIImage(data: contact.image ?? Data()) ?? UIImage())
Upvotes: 3