Swift iOS 9通讯录访问

前端之家收集整理的这篇文章主要介绍了Swift iOS 9通讯录访问前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原创Blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=list
我的stackoverflow


前言:在iOS 9之前,一直使用AddressBook这个framework来访问用户通讯录。但是在iOS 9中,AddressBook被废弃了,转而使用Contacts Framework。


文档


Demo效果

下载链接


请求访问权限

相关类
CNContactStore(线程安全)

CNContactStore代表了实际设备上存储,通过这个类可以
- 检查当前的通讯录访问权限
- 请求访问通讯录权限
- fetch通讯录内容支持按条件fetch,和core data 类似)
- 保存到通讯录

CNContact(线程安全)

表示通讯录中一位联系人的Model类,和NSDictionary类似,他有一个子类是可变的CNMutableContact

示例代码
保存一个store对象,Demo中采用单例
注意,Swift中单例这么写是线程安全的

  1. class ContactsStore{
  2. static let sharedStore = CNContactStore()
  3. }

请求权限

  1. let authStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
  2. let authStatus = ContactsStore.sharedStore.authorizationStatusForEntityType(CNEntityType.Contacts)
  3. if authStatus == CNAuthorizationStatus.Denied || authStatus == CNAuthorizationStatus.NotDetermined{
  4. self.contactsStore.requestAccessForEntityType(CNEntityType.Contacts,completionHandler: { (result,error) -> Void in
  5. if result == false{
  6. let alert = UIAlertController(title: "警告",message: "请在设置中允许通讯录访问,否则App无法正常使用",preferredStyle: UIAlertControllerStyle.Alert)
  7. alert.addAction(UIAlertAction(title: "确定",style: UIAlertActionStyle.Cancel,handler: nil))
  8. self.presentViewController(alert,animated: true,completion: nil)
  9. }
  10. })
  11. }

调用系统的ContactsPickerViewController

  1. 让ViewController实现CNContactPickerDelegate协议
    实现如下方法,处理选中的结果
  1. func contactPicker(picker: CNContactPickerViewController,didSelectContact contact: CNContact) {
  2. if let phoneNumber = contact.phoneNumbers.first?.value as? CNPhoneNumber{
  3. self.textfield.text = phoneNumber.stringValue
  4. }
  5. }

然后,模态展示

  1. let contactsVC = CNContactPickerViewController()
  2. contactsVC.delegate = self;
  3. presentViewController(contactsVC,animated:true,completion: nil)

查询全部通讯录

注意,要先指明需要fetch的属性

因为enumerateContactsWithFetchRequest这个函数会抛出异常,所以要用do-try-catch包括起来

  1. let keys = [CNContactGivenNameKey,CNContactPhoneNumbersKey,CNContactThumbnailImageDataKey]
  2. let fetchAllRequest = CNContactFetchRequest(keysToFetch:keys)
  3. do{
  4. try ContactsStore.sharedStore.enumerateContactsWithFetchRequest(fetchAllRequest) { (contact,pointer) -> Void in
  5. self.contacts.append(contact)
  6. }
  7. }catch{
  8.  
  9. }

条件查询

条件查询在示例工程中未列出,按照如下步骤查询
使用如下CNContact方法创建NSPredicate对象

  1. predicateForContactsMatchingName:
  2. predicateForContactsWithIdentifiers:
  3. ...

使用CNContactStore的
- unifiedContactsMatchingPredicate:keysToFetch:error:
查询


添加

摘自Swift2.1文档

  1. import Contacts
  2.  
  3. // Creating a mutable object to add to the contact
  4. let contact = CNMutableContact()
  5.  
  6. contact.imageData = NSData() // The profile picture as a NSData object
  7.  
  8. contact.givenName = "John"
  9. contact.familyName = "Appleseed"
  10.  
  11. let homeEmail = CNLabeledValue(label:CNLabelHome,value:"john@example.com")
  12. let workEmail = CNLabeledValue(label:CNLabelWork,value:"j.appleseed@icloud.com")
  13. contact.emailAddresses = [homeEmail,workEmail]
  14.  
  15. contact.phoneNumbers = [CNLabeledValue(
  16. label:CNLabelPhoneNumberiPhone,value:CNPhoneNumber(stringValue:"(408) 555-0126"))]
  17.  
  18. let homeAddress = CNMutablePostalAddress()
  19. homeAddress.street = "1 Infinite Loop"
  20. homeAddress.city = "Cupertino"
  21. homeAddress.state = "CA"
  22. homeAddress.postalCode = "95014"
  23. contact.postalAddresses = [CNLabeledValue(label:CNLabelHome,value:homeAddress)]
  24.  
  25. let birthday = NSDateComponents()
  26. birthday.day = 1
  27. birthday.month = 4
  28. birthday.year = 1988 // You can omit the year value for a yearless birthday
  29. contact.birthday = birthday
  30.  
  31. // Saving the newly created contact
  32. let store = CNContactStore()
  33. let saveRequest = CNSaveRequest()
  34. saveRequest.addContact(contact,toContainerWithIdentifier:nil)
  35. try store.executeSaveRequest(saveRequest)

本地化/格式化

几个常用的类

  • CNContactFormatter
  • CNPostalAddressFormatter
  • CNContact.localizedStringForKey
  • CNLabeledValue.localizedStringForLabel

举例

从Contact中拼接出全名

  1. let fullName = CNContactFormatter.stringFromContact(contact,style: .FullName)
  2. print(fullName)
  3. // John Appleseed

邮政地址

  1. let postalString = CNPostalAddressFormatter.stringFromPostalAddress(homeAddress)
  2. print(postalString)
  3. // 1 Infinite Loop
  4. // Cupertino
  5. // CA
  6. // 95014

对通讯录的内置Key获取

  1. let displayName = CNContact.localizedStringForKey(CNContactNicknameKey)
  2. print(displayName)
  3. // 昵称,在中文条件下

最后

欢迎关注我的CSDN博客,在我每个月都会更新10篇左右的iOS 文章,源码都是Swift的。

猜你在找的Swift相关文章