iOS-通讯录(无界面)
通讯录(无界面)
#import "AppDelegate.h"
#import <AddressBook/AddressBook.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/*
kABAuthorizationStatusNotDetermined = 0, 没有决定是否授权
kABAuthorizationStatusRestricted, 受限制
kABAuthorizationStatusDenied, 拒绝
kABAuthorizationStatusAuthorized 授权
*/
//1.需要申请授权
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) {
if (granted == YES) {
NSLog(@"授权成功!");
}else{
NSLog(@"授权失败");
}
});
}
return YES;
}
#import "ViewController.h"
#import <AddressBook/AddressBook.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//2.获取数据
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//1.创建一个通讯录
ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
//获取所有联系人 其实就是记录 ABMultiValueRef record(记录)
CFArrayRef multiValue = ABAddressBookCopyArrayOfAllPeople(book);
CFIndex count = CFArrayGetCount(multiValue);
for (CFIndex i = 0; i < count ; ++i) {
ABRecordRef record = CFArrayGetValueAtIndex(multiValue, i);
//姓名
CFStringRef first = ABRecordCopyValue(record, kABPersonFirstNameProperty);
CFStringRef last = ABRecordCopyValue(record, kABPersonLastNameProperty);
NSString *firstStr = (__bridge_transfer NSString *)(first);
NSString *lastStr = (__bridge_transfer NSString *)(last);
NSLog(@"%@ %@ ",firstStr,lastStr);
//电话号码
ABMultiValueRef multiPhones = ABRecordCopyValue(record, kABPersonPhoneProperty);
CFIndex countPhone = ABMultiValueGetCount(multiPhones);
for (CFIndex j = 0; j < countPhone; ++j) {
CFStringRef phone = ABMultiValueCopyValueAtIndex(multiPhones, j);
NSString *phoneStr = (__bridge_transfer NSString *)phone;
NSLog(@"phone = %@",phoneStr);
}
CFRelease(multiPhones);
}
CFRelease(multiValue);
CFRelease(book);
}