gpt4 book ai didi

ios - 如何从 CNContactPickerViewController 获取选定的 contactProperty

转载 作者:行者123 更新时间:2023-11-29 05:29:45 25 4
gpt4 key购买 nike

我目前可以从联系人应用程序获取联系人,但我面临的问题是,如果联系人有超过 1 部手机,我需要能够选择要导入到我的应用程序的联系人数字,我总是得到第一个数字,这是我正在使用的代码:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {

let numbers = contactProperty.contact.phoneNumbers.first
let firstName = contactProperty.contact.givenName
let lastName = contactProperty.contact.familyName
let phoneNumber = (numbers?.value)?.stringValue ?? ""

/// Duplicate phone numbers will not be saved
if phoneNumbers.contains(phoneNumber) {
return
}
/// Saving selected contact in Core Data
CoreDataManager.sharedInstance.savePhoneNumberInCoreData(FirstName: firstName, LastName: lastName, PhoneNumber: phoneNumber)

DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
}

线路问题:

contactProperty.contact.phoneNumbers.first

有两个选项仅适用于 contactProperty.contact.phoneNumbers .first.last

如果有像.selected之类的东西,就可以解决问题。

最佳答案

您可以使用一个名为“主要电话号码”的东西

var phoneNumber: String?

if let mainNumber = numbers.first(where: { $0.label == CNLabelPhoneNumberMain }) {
phoneNumber = mainNumber.value.stringValue
} else {
phoneNumber = numbers.first?.value.stringValue //or some other default value
}

请注意,我将 numbers 的定义更改为电话号码数组

let numbers = contactProperty.contact.phoneNumbers

完整代码:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {

let numbers = contactProperty.contact.phoneNumbers
var phoneNumber: String?

if let mainNumber = numbers.first(where: { $0.label == CNLabelPhoneNumberMain }) {
phoneNumber = mainNumber.value.stringValue
} else {
phoneNumber = numbers.first?.value.stringValue //or some other default value
}

if phoneNumber == nil || phoneNumbers.contains(phoneNumber) {
return
}

let firstName = contactProperty.contact.givenName
let lastName = contactProperty.contact.familyName

CoreDataManager.sharedInstance.savePhoneNumberInCoreData(FirstName: firstName, LastName: lastName, PhoneNumber: phoneNumber)

DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
}

关于ios - 如何从 CNContactPickerViewController 获取选定的 contactProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com