您的位置:首页 > 移动开发 > IOS开发

通讯录, 获取联系人, 删除联系人

2016-01-28 12:00 501 查看
<pre name="code" class="objc">//
//  BuddyManager.h
//  wincall
//
//  Created by User on 15/12/8.
//  Copyright © 2015年 Zero. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <AddressBook/AddressBook.h>

@interface ContactsManager : NSObject

@property (nonatomic, strong) NSArray *persons;

@property (nonatomic, strong) NSMutableArray *cpassBuddies;

@property (nonatomic) ABAddressBookRef addressBook;
@property (nonatomic, assign) BOOL isimage;

+ (instancetype)share;

-(void)getPersonInfo;

+ (NSString *)firstCharactor:(NSString *)aString;

+ (void)groupingByInitialWithDataSource:(NSArray*)dataSource resureBlock:(void (^)(NSMutableDictionary*result,NSArray *allkeys))block ;

+ (NSString*)castSpecialChar:(NSString*)cha;
//删除联系人
- (BOOL)deletePerson:(ABRecordRef)ref;
+(NSMutableArray *)searchScopeWithSearchText:(NSString *)searchText FromeArray:(NSArray *)array;

@end

//
//  BuddyManager.m
//  wincall
//
//  Created by User on 15/12/8.
//  Copyright © 2015年 Zero. All rights reserved.
//

#import "ContactsManager.h"
#import "ContactsModel.h"
#import "PinYinForObjc.h"

#define emptyString(value)   value == nil?@"":value

@implementation ContactsManager

- (instancetype)init {
self = [super init];

return self;
}
+(instancetype)share
{
static ContactsManager* base = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
base = [[ContactsManager alloc] init];;
//        base.addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
});
return base;
}

#pragma mark 获取通讯录内容
-(void)getPersonInfo{
//取得本地通信录名柄

NSMutableArray *array = [[NSMutableArray alloc] init];
//    ABAddressBookRef addBook = [[ContactsManager share] addressBook];
ABAddressBookRef addBook = ABAddressBookCreateWithOptions(NULL, NULL);

//等待同意后向下执行创建信号,发出信号, 等待信号
dispatch_semaphore_t sema = dispatch_semaphore_create(0);        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool granted, CFErrorRef error)                                                 {
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

//取得本地所有联系人记录
CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addBook);
for(int i = 0; i < CFArrayGetCount(results); i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(results, i);
//读取firstname
NSString *personName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);

//读取lastname
NSString *lastname = (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);

//读取middlename
NSString *middlename = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);

NSString *name = [NSString stringWithFormat:@"%@%@%@",emptyString(lastname),emptyString(personName),emptyString(middlename)];
//读取organization公司
NSString *organization = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);

NSData *image = (__bridge NSData*)ABPersonCopyImageData(person);
UIImage *headImage = [UIImage imageWithData:image];
if (!headImage) {
headImage = [self backgroundImageWithRow];
_isimage = NO;
} else {
_isimage = YES;
}

//读取电话多值
ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
if (ABMultiValueGetCount(phone) == 0) {
ContactsModel *model = [[ContactsModel alloc] init];
//读取照片
model.image = headImage;
model.isImage = _isimage;

//读取名字
if(name.length == 0){
name = organization;

}

model.modelName = name;
if(name != nil) {
model.pinyin = [ContactsManager hanziToPinyin:name];

if(model.pinyin.length >0) {

model.fristCharacter = [NSString stringWithFormat:@"%c",[model.pinyin characterAtIndex:0]];
}
}
model.person = person;
[array addObject:model];

}

for (int k = 0; k<ABMultiValueGetCount(phone); k++)
{
ContactsModel *model = [[ContactsModel alloc] init];

NSMutableArray *phones = [[NSMutableArray alloc] init];
NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
personPhone =[ContactsManager castSpecialChar:personPhone];

if (personPhone.length > 10) {
NSString *cut = [personPhone substringToIndex:[personPhone length] - 6];

if ([cut hasPrefix:@"96833"] || [cut hasPrefix:@"02196833"]) {
//                    [wincalls addObject:personPhone];
model.wincallPhone = personPhone;
model.iswincall = YES;
NSLog(@"phone   %@--%@",name,personPhone);
}else {
NSLog(@"wicnall %@--%@",name,personPhone);
model.iswincall = NO;
model.phone = personPhone;

}

} else {
NSLog(@"wicnall %@--%@",name,personPhone);
model.iswincall = NO;
model.phone = personPhone;

}

//读取照片
model.image = headImage;
model.isImage = _isimage;

//读取名字
if(name.length == 0){
name = organization;

}

model.modelName = name;
if(name != nil) {
model.pinyin = [ContactsManager hanziToPinyin:name];

if(model.pinyin.length >0) {

model.fristCharacter = [NSString stringWithFormat:@"%c",[model.pinyin characterAtIndex:0]];
}
}

model.person = person;
[array addObject:model];

[phones addObject:personPhone];
model.phoneValues = phones;
}
}
_persons = array;

CFRelease(results);//new
}

//随机背景图片
- (UIImage*)backgroundImageWithRow{
UIImage *aquaImage = [UIImage imageNamed:@"aqua"];
UIImage *blueImage = [UIImage imageNamed:@"blue"];
UIImage *greenImage = [UIImage imageNamed:@"green"];
UIImage *pinkImage = [UIImage imageNamed:@"pink"];
UIImage *purpleImage = [UIImage imageNamed:@"purple"];
UIImage *yellowImage = [UIImage imageNamed:@"yellow"];
NSArray *array = @[aquaImage, blueImage, greenImage, pinkImage, purpleImage, purpleImage, yellowImage];
int i = arc4random() %6;
return array[i];
}

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)firstCharactor:(NSString *)aString
{
if (aString == nil) {
return aString;
}
//转成了可变字符串
NSMutableString *str = [NSMutableString stringWithString:aString];
//先转换为带声调的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
//再转换为不带声调的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
//转化为大写拼音
NSString *pinYin = [str capitalizedString];
//获取并返回首字母
//    return [pinYin substringToIndex:1];
return pinYin;
}

//根据封装字典

#pragma mark 根据首字母分组
+ (void)groupingByInitialWithDataSource:(NSArray*)dataSource resureBlock:(void (^)(NSMutableDictionary*result,NSArray *allkeys))block
{

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSMutableArray * allData = [[NSMutableArray alloc] init];

for (int i = 0;i<dataSource.count;i++) {
NSMutableArray * temp = [[NSMutableArray alloc] init];

4000
id obj = [dataSource objectAtIndex:i];
ContactsModel *model;

NSString *pinyin;
NSString *fristCharacter;
if([obj isKindOfClass:[ContactsModel class]]){
model = obj;
pinyin = [ContactsManager hanziToPinyin:model.modelName];

}
int asciiCode;
if(pinyin.length > 0){
asciiCode = [pinyin characterAtIndex:0];
fristCharacter = [NSString stringWithFormat:@"%c",[pinyin characterAtIndex:0]];
}else{
asciiCode = 0;
}

/*
*如果首字符满足条件,则正常分组;否则 分到 ‘#’,存储到allData里
*/
if(('a'<=asciiCode&&asciiCode<='z')||('A'<=asciiCode&&asciiCode<='Z')) {

if([dic objectForKey:fristCharacter]) {
NSArray *exist = [dic objectForKey:fristCharacter];
[temp addObjectsFromArray:exist];
[temp addObject:obj];
}else{
[temp addObject:obj];

}
[dic setObject:temp forKey:fristCharacter];
}else{

[allData addObject:obj];
}
}
if(allData.count > 0){
[dic setObject:allData forKey:@"a"];
}
//Key值排序
NSArray *_keys = [dic allKeys];
_keys = [_keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
NSComparisonResult result = [obj1 compare:obj2];

return result == NSOrderedDescending;
}];

block(dic,_keys);

}

//删除联系人
- (BOOL)deletePerson:(ABRecordRef)ref{

ABAddressBookRef address = [[ContactsManager share]addressBook];
CFErrorRef error = nil;
ABAddressBookRemoveRecord(address, ref, &error);
//保存电话本
return  ABAddressBookSave(address,&error);
}

#pragma mark -去重复对象
+ (NSMutableArray *)arrayWithMemberIsOnly:(NSMutableArray *)array
{
NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [array count]; i++) {

if ([categoryArray containsObject:[array objectAtIndex:i]] == NO){
[categoryArray addObject:[array objectAtIndex:i]];

}
}
return categoryArray;
}

/*
*去掉特殊字符
*/
+ (NSString*)castSpecialChar:(NSString*)cha{

cha = [cha stringByReplacingOccurrencesOfString:@"+86" withString:@""];
cha = [cha stringByReplacingOccurrencesOfString:@"-" withString:@""];
cha = [cha stringByReplacingOccurrencesOfString:@" " withString:@""];
cha = [cha stringByReplacingOccurrencesOfString:@" " withString:@""];
cha = [cha stringByReplacingOccurrencesOfString:@"(" withString:@""];
cha = [cha stringByReplacingOccurrencesOfString:@")" withString:@""];

NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%+-*=_\\|~<>$€^• '@#$%^&*()_'\""];
return [[cha componentsSeparatedByCharactersInSet: set]componentsJoinedByString:@""];
}

#pragma mark - 汉字转拼音
+ (NSString*)hanziToPinyin:(NSString*)hanzi{
HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
[outputFormat setToneType:ToneTypeWithoutTone];
[outputFormat setVCharType:VCharTypeWithV];
[outputFormat setCaseType:CaseTypeLowercase];
NSString *outputPinyin = [PinyinHelper toHanyuPinyinStringWithNSString:hanzi
withHanyuPinyinOutputFormat:outputFormat
withNSString:@""];
return [outputPinyin uppercaseString];
}

//搜索
+ (BOOL)isIncludeChineseInString:(NSString*)str {
for (int i=0; i<str.length; i++) {
unichar ch = [str characterAtIndex:i];
if (0x4e00 < ch  && ch < 0x9fff) {
return true;
}
}
return false;
}

+(NSMutableArray *)searchScopeWithSearchText:(NSString *)searchText FromeArray:(NSArray *)array {
NSMutableArray * searchResults = [[NSMutableArray alloc]init];

if (searchText.length>0&&![ContactsManager isIncludeChineseInString:searchText]) {
for (int i=0; i<array.count; i++) {
ContactsModel *model = array[i];
NSString *name = model.modelName;
if ([ContactsManager isIncludeChineseInString:name]) {
NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:name];
NSRange titleResult=[tempPinYinStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResult.length>0) {
[searchResults addObject:name];
}
NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:name];
NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleHeadResult.length>0) {
[searchResults addObject:name];
}
}
else {
NSRange titleResult=[name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResult.length>0) {
[searchResults addObject:name];
}
}
}
} else if (searchText.length>0&&[ContactsManager isIncludeChineseInString:searchText]) {
for (NSString *tempStr in array) {
NSRange titleResult=[tempStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResult.length>0) {
[searchResults addObject:tempStr];
}
}
}
return searchResults;

}

@end



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 通讯录