以编程方式请求访问联系人 [英] Programmatically Request Access to Contacts
问题描述
自从更新到iOS 6后,我注意到我在iPhone地址簿中添加联系人的代码不再有效。我认为这是一个与权限相关的问题,因为Apple在访问联系人之前现在需要用户许可(修复(向下滚动到页面中间的隐私),必须先获得对地址簿的访问权限才能访问以编程方式访问。以下是我最终要做的事情。
#import< AddressBookUI / AddressBookUI.h>
//请求授权给地址簿
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL,NULL);
if(ABAddressBookGetAuthorizationStatus()== kABAuthorizationStatusNotDetermined){
ABAddressBookRequestAccessWithCompletion(addressBookRef,^(bool grant,CFErrorRef error){
if(grant){
//第一次访问已被授予,添加联系人
[self _addContactToAddressBook];
} else {
//用户拒绝访问
//显示警告告诉用户联系人无法访问加上
}
});
}
else if(ABAddressBookGetAuthorizationStatus()== kABAuthorizationStatusAuthorized){
//用户先前已授予访问权限,添加联系人
[self _addContactToAddressBook];
}
else {
//用户先前已拒绝访问
//发送提醒告知用户更改设置应用中的隐私设置
}
更新适用于iOS 9及更高版本:
来自Apple网站:
重要
地址簿界面在iOS 9中不推荐使用框架。请改用ContactsUI框架中定义的API。要了解详情,请参阅 ContactsUI
Since updating to iOS 6 I've noticed that my code to add a contact to iPhone's address book no longer works. I believe this is a permission related problem, since Apple now requires user permission before accessing contacts (fixing this issue).
I expected the app to automatically ask permission to access contacts, like in the screenshot below, but it doesn't. Trying to add the contact just fails with ABAddressBookErrorDomain error 1
.
Do I need to programmatically launch the access to contacts request dialog? How is that done?
As per this documentation on apple's site (scroll down to Privacy in the middle of the page), access to the address book must be granted before it can be access programmatically. Here is what I ended up doing.
#import <AddressBookUI/AddressBookUI.h>
// Request authorization to Address Book
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if (granted) {
// First time access has been granted, add the contact
[self _addContactToAddressBook];
} else {
// User denied access
// Display an alert telling user the contact could not be added
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self _addContactToAddressBook];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
Update For iOS 9 and later:
From Apple website :
Important
The Address Book UI framework is deprecated in iOS 9. Use the APIs defined in the ContactsUI framework instead. To learn more, see ContactsUI
这篇关于以编程方式请求访问联系人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!