我正在尝试与我的 iPhone 上所有拥有特定代码(该代码存储在联系人的即时消息字段中)的联系人合作。
获取代码:
func fetchAllContacts() async {
// Get access to the Contacts Store
let store = CNContactStore()
// Specify which data keys we ant to fetch
let keys = [CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactInstantMessageAddressesKey] as [CNKeyDescriptor]
// Create an fetch request
let fetchRequest = CNContactFetchRequest(keysToFetch: keys)
// Call method to fetch all contacts
do {
try store.enumerateContacts(with: fetchRequest, usingBlock: { contact, result in
if !contact.instantMessageAddresses.isEmpty {
print(contact.givenName)
print(contact.instantMessageAddresses)
}
})
}
catch {
print("Error")
}
}
工作正常,以下联系信息打印到控制台:
Roman
[<CNLabeledValue: 0x282783100: identifier=0E327523-281C-49D7-A4A1-7E5FF9F10F1C, label=(nil), value=<CNMutableInstantMessageAddress: 0x283ccdda0: username=01 1244 131 01, userIdentifier=(nil), service=, teamIdentifier=(nil), bundleIdentifiers=(nil)>, iOSLegacyIdentifier=0>]
如何获取用户名字符串?我需要这个字符串“01 1244 131 01”,但我不知道如何在变量中读取这个字符串。
我尝试了以下操作,但它引发了错误:
print ("C-Value: \(contact.value(forKey: "username")!)")
正如您从 instantMessageAddresses 的文档中看到的:
对象数组,每个对象都有一个标签和CNLabeledValue
值。CNInstantMessageAddress
您可以使用以下命令代替
print(contact.instantMessageAddresses)
来打印第一个地址(如果有):
print(contact.instantMessageAddresses.first?.value.username)
当然,如果联系人有多个即时消息地址,您将需要遍历数组并访问所有地址。
这将创建一个用户名数组:
let usernames = contact.instantMessageAddresses.map { $0.value.username }