Fetch Contact Image - SwiftUI

ぃ、小莉子 提交于 2021-01-28 04:05:07

问题


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?


回答1:


Your contact image is Data, so you should create Image in different way, like

Image(uiImage: UIImage(data: contact.image ?? Data()) ?? UIImage())


来源:https://stackoverflow.com/questions/64510100/fetch-contact-image-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!