【发布时间】: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()
}
}
}
【问题讨论】:
-
这是否回答了您的问题stackoverflow.com/questions/64510100/…?
-
是的,事实上我错过了在请求中添加相应的键-谢谢:-)
标签: swiftui