尝试检索手机号码的联系人新手。我有地址名称电子邮件,但无法弄清楚手机。这就是我得到的。标有**
的部分是我出错的地方。
if let oldContact = self.contactItem {
let store = CNContactStore()
do {
let mykeysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactEmailAddressesKey, CNContactPostalAddressesKey,CNContactImageDataKey, CNContactImageDataAvailableKey,CNContactPhoneNumbersKey]
let contact = try store.unifiedContactWithIdentifier(oldContact.identifier, keysToFetch: mykeysToFetch)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if contact.imageDataAvailable {
if let data = contact.imageData {
self.contactImage.image = UIImage(data: data)
}
}
self.fullName.text = CNContactFormatter().stringFromContact(contact)
self.email.text = contact.emailAddresses.first?.value as? String
self.phoneNumber.text = contact.phoneNumbers.first?.value as? String
**if contact.isKeyAvailable(CNContactPhoneNumbersKey){
if let phoneNum = contact.phoneNumbers.first?.value as? String {
self.phoneNumber.text = phoneNum as String
}
}**
if contact.isKeyAvailable(CNContactPostalAddressesKey) {
if let postalAddress = contact.postalAddresses.first?.value as? CNPostalAddress {
self.address.text = CNPostalAddressFormatter().stringFromPostalAddress(postalAddress)
} else {
self.address.text = "No Address"
}
}
})
} catch {
print(error)
}
}
答案 0 :(得分:4)
如果您想要联系人的移动电话列表,请查看phoneNumbers
这是CNLabeledValue
的数组,并查找label
CNLabelPhoneNumberMobile
的移动电话}或CNLabelPhoneNumberiPhone
。
例如,您可以执行以下操作:
let mobilePhoneLabels = Set<String>(arrayLiteral: CNLabelPhoneNumberMobile, CNLabelPhoneNumberiPhone, "cell", "mobile") // use whatever you want here; you might want to include a few strings like shown here to catch any common custom permutations user may have used
let mobileNumbers = contact.phoneNumbers.filter { mobilePhoneLabels.contains($0.label) && $0.value is CNPhoneNumber }
.map { ($0.value as! CNPhoneNumber).stringValue }
所以如果你想要第一个:
let mobileNumber = mobileNumbers.first ?? "" // or use `if let` syntax
或者如果你想要一个列表的字符串表示:
let mobileNumberString = mobileNumbers.joinWithSeparator(" ; ")
您对这一系列手机号码的处理取决于您,但希望这说明了基本的想法。