【问题标题】:Fetch Contact Image - SwiftUI获取联系人图片 - SwiftUI
【发布时间】:2021-02-07 02:45:18
【问题描述】:

我正在尝试获取给定contact 的图像属性。这是我得到的:

型号

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))
     }
}

查看

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)))

            }
        } 
    }
}

我得到的错误是紫色的,然后说

运行时:SwiftUI:在 /private/var/containers/Bundle/Application/...等的资产目录中找不到名为“可选(38321 字节)”的图像

显然,我在 Apple 提供的 Contacts 应用程序中有联系人图片。

有什么想法吗?

【问题讨论】:

    标签: swift swiftui cncontact cncontactstore


    【解决方案1】:

    你的联系人图片是Data,所以你应该用不同的方式创建Image,比如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2014-01-19
      • 2014-01-14
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多