我有一个自定义用户类,用于存储用户的电话号码. class User { let phoneNumber: String} 如何从用户联系簿获取相应的联系人? 我尝试了以下但似乎这只适用于联系人名称,因为我总是得到零:
class User { let phoneNumber: String }
如何从用户联系簿获取相应的联系人?
我尝试了以下但似乎这只适用于联系人名称,因为我总是得到零:
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
我在文档中搜索过但我找不到合适的解决方案.
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) } } })
这是我的方式,你可以进行测试