// 是否开通了访问权限
func getContacts(){
phoneStr = ""
let store = CNContactStore()
let authorizationStatus = CNContactStore.authorizationStatusForEntityType(.Contacts)
switch authorizationStatus {
case .Authorized:
self.retrieveContactsWithStore(store)
case .Denied, .NotDetermined:
store.requestAccessForEntityType(.Contacts, completionHandler: { (access: Bool, error: NSError?) in
if access{
self.retrieveContactsWithStore(store)
}else{
self.view.viewAlert(self, title: "提示", msg: "\"\(ToolKit.getProjectName())\"请求访问您的通讯录", cancelButtonTitle: "取消", otherButtonTitle: "去设置", handler: { (buttonIndex, action) in
if buttonIndex == 1{
let settingUrl = NSURL(string: "prefs:root=Privacy&path=CONTACTS")
let application = UIApplication.sharedApplication()
if application.canOpenURL(settingUrl!) {
application.openURL(settingUrl!)
}else{
LoadingAnimation.showError(self, msg: nil)
}
}
})
}
})
default:
break
}
}
// 获取通讯录信息
func retrieveContactsWithStore(store: CNContactStore){
do{
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
CNContactImageDataKey,
CNContactPhoneNumbersKey]
let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)
try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (contact, stop) in
if contact.phoneNumbers.count > 0{
let labelValue = contact.phoneNumbers[0] as CNLabeledValue
let phoneNumer = (labelValue.value as! CNPhoneNumber).valueForKey("digits")
if phoneNumer == nil{
self.phoneStr = "\(self.phoneStr),{\"phoneNum\":\"\"}"
}else{
self.phoneStr = "\(self.phoneStr),{\"phoneNum\":\"\(phoneNumer!)\"}"
}
}
})
}catch{
}
}
//往通讯录里添加数据
let saveRequest = CNSaveRequest()
let contactsData: JSON = data["data"]
for i in 0 ..< contactsData.count {
let contact = CNMutableContact()
contact.givenName = "name\(contactsData[i]["Id"].stringValue)"
let phoneFirst = CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue: contactsData[i]["PhoneNum"].stringValue))
contact.phoneNumbers = [phoneFirst]
saveRequest.addContact(contact, toContainerWithIdentifier: nil)
}
let store = CNContactStore()
do{
try store.executeSaveRequest(saveRequest)
}catch{
}
访问通讯录Contacts
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1.Contacts的四种用户访问状态 代码: CNAuthorizationStatus status = [C...
- 前言 功能介绍: 点击按钮后从屏幕底部弹出手机通讯录界面, 点击联系人手机号后, 联系人姓名以及手机号显示到指定的...