尝试检索移动电话号码的联系人新手。我有地址,名字,电子邮件,但不能识别手机。这就是我得到的。标有**的部分就是我出错的地方。
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)
}
}发布于 2016-05-28 12:34:10
如果您想要联系人的移动电话列表,可以查看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(" ; ")如何处理这一组手机号码取决于您,但希望这说明了基本思想。
https://stackoverflow.com/questions/37494537
复制相似问题