【问题标题】:How to get and display contact photos on iOS with SwiftUI?如何使用 SwiftUI 在 iOS 上获取和显示联系人照片?
【发布时间】:2020-11-23 09:31:30
【问题描述】:

我有一个正在运行的脚本,可以使用 SwiftUI 在 iOS 上读取和显示所有联系人,但我也在努力显示联系人图像。当我调试代码时,所有联系人的 imageData 似乎都是空的,并且 hasImageData 是假的。一般来说,联系人是从 Google 同步到 iPhone 的,但出于测试目的,我将 iPhone 上的照片添加到一些联系人,结果相同 - 没有结果。

希望任何人都知道出了什么问题:-)


import SwiftUI
import Contacts

struct FetchedContact {
    var id: String
    var firstName: String
    var lastName: String
    var telephone: String
}

func getContacts() -> [FetchedContact] {
    
    var contacts = [FetchedContact]()
    
    let store = CNContactStore()
    store.requestAccess(for: .contacts) { (granted, error) in
        if let error = error {
            print("failed to request access", error)
            return
        }
        if granted {
            let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
            let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
            do {
                try store.enumerateContacts(with: request, usingBlock: { (contact, stopPointer) in
                    contacts.append(FetchedContact(id: contact.identifier, firstName: contact.givenName, lastName: contact.familyName, telephone: contact.phoneNumbers.first?.value.stringValue ?? ""))
                })
            } catch let error {
                print("Failed to enumerate contact", error)
            }
        } else {
            print("access denied")
        }
        
    }
    
    contacts.sort {
        $0.firstName < $1.firstName
    }
    
    contacts.sort {
        $0.lastName < $1.lastName
    }
    
    return contacts
    
}

struct ContactListView: View {
    
    @State var contacts = [FetchedContact]()
    
    var body: some View {
        VStack {
            Button(action: {
                self.contacts = getContacts()
            }) {
                Text("Update contacts")
            }
            .padding()
            Text("\(self.contacts.count) contacts found")
                .padding()
            List(self.contacts, id: \.id) { contact in
                Text("\(contact.lastName), \(contact.firstName)")
            }
            .padding(.vertical)
            
        }
        .navigationTitle("Contact List View")
    }
    
}

struct ContactListView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView() {
            ContactListView()
        }
    }
}

【问题讨论】:

标签: swiftui


【解决方案1】:

解决方案:

  1. 向查询中添加所需的键

    let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey]

  2. 修改图片显示

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

【讨论】:

    猜你喜欢
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2013-09-16
    • 2011-11-12
    • 1970-01-01
    相关资源
    最近更新 更多