尝试检索手机号码的新联系人。我有地址名称电子邮件,但无法识别手机号码。这就是我得到的。标有 **
的部分是我出错的地方。
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)
}
}
最佳答案
如果您想要联系人的手机列表,您可以查看 phoneNumbers
(它是 CNLabeledValue
数组),并查找带有 标签的手机
。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(" ; ")
如何处理这组手机号码取决于您,但希望这能说明基本想法。
关于swift - 如何从联系人框架检索电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494537/