我有一个自定义User
课程,用于存储用户的电话号码。
class User {
let phoneNumber: String
}
如何从用户联系簿获取相应的联系人?
我尝试了以下内容,但似乎只适用于联系人姓名,因为我总是得到nil
:
let predicate = CNContact.predicateForContactsMatchingName(userInstance.phoneNumber)
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPhoneNumbersKey]
// Is already permitted
try! CNContactStore().unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch).first // This returns nil
我在文档中搜索过但我找不到合适的解决方案。
答案 0 :(得分:4)
let contactStroe = CNContactStore()
let keysToFetch = [
CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey,
CNContactImageDataAvailableKey,
CNContactThumbnailImageDataKey]
contactStroe.requestAccessForEntityType(.Contacts, completionHandler: { (granted, error) -> Void in
if granted {
let predicate = CNContact.predicateForContactsInContainerWithIdentifier(contactStroe.defaultContainerIdentifier())
var contacts: [CNContact]! = []
do {
contacts = try contactStroe.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch)// [CNContact]
}catch {
}
for contact in contacts {
var phoneStr = ""
var nameStr = ""
var number: CNPhoneNumber!
if contact.phoneNumbers.count > 0 {
number = contact.phoneNumbers[0].value as! CNPhoneNumber
phoneStr = number.stringValue.stringByReplacingOccurrencesOfString("-", withString: "")
}
nameStr = contact.familyName + contact.givenName
if !nameStr.isEmpty && !phoneStr.isEmpty {
let friend = YFriendsModel()
friend.name = nameStr
friend.phone = phoneStr
self.friendArr.append(friend)
}
}
})
这是我的方式,你可以进行测试
答案 1 :(得分:3)
你不能。
这是一个愚蠢的解决方案,是一个巨大的解决方法。
[String : Contact]
然后,您可以使用contacts[phone_number]?
答案 2 :(得分:0)
Swift 3 一个很好的解决方案,也注重效率:
func getAllContacts() {
let status = CNContactStore.authorizationStatus(for: CNEntityType.contacts) as CNAuthorizationStatus
if status == CNAuthorizationStatus.denied {
self.showAccessContactsDeniedAlert()
return
}
let contactStore = CNContactStore()
let keysToFetch = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey,
CNContactImageDataAvailableKey,
CNContactThumbnailImageDataKey] as [Any]
let request = CNContactFetchRequest(keysToFetch:keysToFetch as! [CNKeyDescriptor])
do {
try contactStore.enumerateContacts(with: request, usingBlock: { (contact:CNContact, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
print(contact)
for email in contact.emailAddresses {
var dict = [String:String]()
dict["name"] = contact.familyName + contact.givenName
dict["email"] = email.value
self.allContacts.add(dict)
}
})
} catch {
//catch
}
}
在这种情况下,我将名称和电子邮件保存到dict中,然后将其添加到名为allContacts的类变量中。
请注意,联系人可以有多封电子邮件,因此我在这种情况下为任何电子邮件地址创建了一个词典