原创Blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=list
我的stackoverflow
文档 Contacts Framework Contacts UI Framework Demo效果前言:在iOS 9之前,一直使用AddressBook这个framework来访问用户通讯录。但是在iOS 9中,AddressBook被废弃了,转而使用Contacts Framework。
下载链接
请求访问权限相关类
CNContactStore(线程安全)
CNContactStore代表了实际设备上存储,通过这个类可以
- 检查当前的通讯录访问权限
- 请求访问通讯录权限
- fetch通讯录内容(支持按条件fetch,和core data 类似)
- 保存到通讯录
CNContact(线程安全)
表示通讯录中一位联系人的Model类,和NSDictionary类似,他有一个子类是可变的CNMutableContact
示例代码
保存一个store对象,Demo中采用单例
注意,Swift中单例这么写是线程安全的
class Contactsstore{ static let sharedStore = CNContactStore()}
请求权限
let authStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts) let authStatus = Contactsstore.sharedStore.authorizationStatusForEntityType(CNEntityType.Contacts) if authStatus == CNAuthorizationStatus.DenIEd || authStatus == CNAuthorizationStatus.NotDetermined{ self.contactsstore.requestAccessForEntityType(CNEntityType.Contacts,completionHandler: { (result,error) -> VoID in if result == false{ let alert = UIAlertController(Title: "警告",message: "请在设置中允许通讯录访问,否则App无法正常使用",preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(Title: "确定",style: UIAlertActionStyle.Cancel,handler: nil)) self.presentVIEwController(alert,animated: true,completion: nil) } }) }调用系统的ContactsPickerVIEwController 让VIEwController实现CNContactPickerDelegate协议
实现如下方法,处理选中的结果
func contactPicker(picker: CNContactPickerVIEwController,dIDSelectContact contact: CNContact) { if let phoneNumber = contact.phoneNumbers.first?.value as? CNPhoneNumber{ self.textfIEld.text = phoneNumber.stringValue } }
然后,模态展示
let contactsVC = CNContactPickerVIEwController() contactsVC.delegate = self; presentVIEwController(contactsVC,animated:true,completion: nil)查询全部通讯录
注意,要先指明需要fetch的属性,
因为enumerateContactsWithFetchRequest
这个函数会抛出异常,所以要用do-try-catch包括起来
let keys = [CNContactGivennameKey,CNContactPhoneNumbersKey,CNContactthumbnailImageDataKey] let fetchAllRequest = CNContactFetchRequest(keysToFetch:keys) do{ try Contactsstore.sharedStore.enumerateContactsWithFetchRequest(fetchAllRequest) { (contact,pointer) -> VoID in self.contacts.append(contact) } }catch{ }条件查询
条件查询在示例工程中未列出,按照如下步骤查询
使用如下CNContact方法创建nspredicate对象
+ predicateForContactsMatchingname:+ predicateForContactsWithIDentifIErs:...
使用CNContactStore的
来查询
- unifIEdContactsMatchingPredicate:keysToFetch:error:
摘自Swift2.1文档
import Contacts// Creating a mutable object to add to the contactlet contact = CNMutableContact()contact.imageData = NSData() // The profile picture as a NSData objectcontact.givenname = "John"contact.familyname = "Appleseed"let homeEmail = CNLabeledValue(label:CNLabelHome,value:"john@example.com")let workEmail = CNLabeledValue(label:CNLabelWork,value:"j.appleseed@icloud.com")contact.emailAddresses = [homeEmail,workEmail]contact.phoneNumbers = [CNLabeledValue( label:CNLabelPhoneNumberiPhone,value:CNPhoneNumber(stringValue:"(408) 555-0126"))]let homeAddress = CNMutablePostalAddress()homeAddress.street = "1 Infinite Loop"homeAddress.city = "Cupertino"homeAddress.state = "CA"homeAddress.postalCode = "95014"contact.postalAddresses = [CNLabeledValue(label:CNLabelHome,value:homeAddress)]let birthday = NSDateComponents()birthday.day = 1birthday.month = 4birthday.year = 1988 // You can omit the year value for a yearless birthdaycontact.birthday = birthday// Saving the newly created contactlet store = CNContactStore()let saveRequest = CNSaveRequest()saveRequest.addContact(contact,toContainerWithIDentifIEr:nil)try store.executeSaveRequest(saveRequest)本地化/格式化
几个常用的类
CNContactFormatter CNPostalAddressFormatter CNContact.localizedStringForKey CNLabeledValue.localizedStringForLabel举例
从Contact中拼接出全名
let fullname = CNContactFormatter.stringFromContact(contact,style: .Fullname)print(fullname)// John Appleseed
邮政地址
let postalString = CNPostalAddressFormatter.stringFromPostalAddress(homeAddress)print(postalString)// 1 Infinite Loop// Cupertino// CA// 95014
对通讯录的内置Key获取
let displayname = CNContact.localizedStringForKey(CNContactNicknameKey)print(displayname)// 昵称,在中文条件下最后
欢迎关注我的CSDN博客,在我每个月都会更新10篇左右的iOS 文章,源码都是Swift的。
总结以上是内存溢出为你收集整理的Swift iOS 9通讯录访问全部内容,希望文章能够帮你解决Swift iOS 9通讯录访问所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)