zz做開(kāi)發(fā)已經(jīng)有一段時(shí)間了, 最近換了新公司, 決定寫(xiě)一些東西記錄一下開(kāi)發(fā)中遇到的坑. 新的公司做的是企業(yè)通訊方面的, 首先遇到的坑就是獲取手機(jī)通訊錄的信息.
由于版本適配的問(wèn)題, 這次采用的是AddressBook這個(gè)框架, 這個(gè)框架在iOS9以后已經(jīng)被Contacts所代替. 以后用到這個(gè)在做記錄吧,
廢話(huà)不多說(shuō)了, 這次要做的就是把通訊錄的信息取出來(lái)然后自定義界面展示.第一步要做的就是引入框架頭文件
import <AddressBook/AddressBook.h>
由于訪(fǎng)問(wèn)的是通訊錄要獲得用戶(hù)授權(quán)所有我們要寫(xiě)一個(gè)方法獲取用戶(hù)的授權(quán) 直接貼上代碼吧
新建一個(gè)model類(lèi), 做聯(lián)系人的model
屬性如下, 因?yàn)槲抑恍枰@幾個(gè)所以就只寫(xiě)著幾個(gè)了
#import "BaseModel.h"
#import <AddressBook/AddressBook.h> @interface ContactBookModel : BaseModel<NSCoding> @property (nonatomic, strong) NSString *name, *telephone, *lastName, *characterName; @property (nonatomic, strong) NSData *imageData; @property (nonatomic, assign) BOOL isSelect;
@end
下面是獲取通訊錄, 我們可以寫(xiě)一個(gè)類(lèi)專(zhuān)門(mén)處理這個(gè), 因?yàn)樵谕ㄓ嶄浀拈_(kāi)發(fā)中 , 我們可以在不同的控制器里會(huì)用到這個(gè)
-(void)getrightFromUser { //這個(gè)變量用于記錄授權(quán)是否成功遇伞,即用戶(hù)是否允許我們?cè)L問(wèn)通訊錄 int __block tip=0; //聲明一個(gè)通訊簿的引用 ABAddressBookRef addBook =nil; //創(chuàng)建通訊簿的引用 addBook=ABAddressBookCreateWithOptions(NULL, NULL); //創(chuàng)建一個(gè)出事信號(hào)量為0的信號(hào) dispatch_semaphore_t sema=dispatch_semaphore_create(0); //申請(qǐng)?jiān)L問(wèn)權(quán)限 ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error) { //greanted為YES是表示用戶(hù)允許月匣,否則為不允許 if (!greanted) { tip=1; } //發(fā)送一次信號(hào) dispatch_semaphore_signal(sema); }); //等待信號(hào)觸發(fā) dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); if (tip) { //我們要在這里做一個(gè)提示框提示用戶(hù)給了授權(quán)才能獲取 return; } //這個(gè)是用來(lái)獲取數(shù)據(jù)的 [self getPhoneContactAddress:addBook]; }
//獲取手機(jī)通訊錄中的信息
- (void)getPhoneContactAddress:(ABAddressBookRef )addBook { //手機(jī)通訊錄獲取存放的數(shù)組 self.contactArray = [NSMutableArray array]; //獲取所有聯(lián)系人的數(shù)組 CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook); //獲取聯(lián)系人總數(shù) CFIndex number = ABAddressBookGetPersonCount(addBook); for (int i = 0; i < number; i++) { ABRecordRef people = CFArrayGetValueAtIndex(allLinkPeople, i); //獲取當(dāng)前聯(lián)系人名字 NSStringfirstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty)); //獲取當(dāng)前聯(lián)系人姓氏 NSString**lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty)); //獲取當(dāng)前聯(lián)系人中間名 NSString *middleName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNameProperty)); // 獲取聯(lián)系人的頭像 NSData *userImage=(__bridge NSData*)(ABPersonCopyImageData(people)); //注意這里的手機(jī)號(hào)是一個(gè)數(shù)組, 因?yàn)橐蝗丝梢杂泻芏鄠€(gè)手機(jī)號(hào), 這里我處理的是一個(gè)手機(jī)號(hào)對(duì)應(yīng)一個(gè)姓名, 多個(gè)手機(jī)號(hào)就有多個(gè)相同的姓名不同手機(jī)號(hào)的模型 NSMutableArray * phoneArr = [[NSMutableArray alloc]init]; ABMultiValueRef phones= ABRecordCopyValue(people, kABPersonPhoneProperty); for (NSInteger j=0; j<ABMultiValueGetCount(phones); j++) { [phoneArr addObject:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j))]; } for (int i = 0; i< phoneArr.count; i++) { ContactBookModel *contactModel = [[ContactBookModel alloc] init];//把名字拼接在一塊 contactModel.name = [NSString stringWithFormat:@"%@%@%@", lastName, middleName, firstName];contactModel.name = [contactModel.name stringByReplacingOccurrencesOfString:@"(null)" withString:@""]; if (contactModel.name == nil || [contactModel.name isEqualToString:@""]) { contactModel.name = @"無(wú)姓名"; } contactModel.imageData = userImage; contactModel.telephone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, i)); contactModel.telephone = [contactModel.telephone stringByReplacingOccurrencesOfString:@"-" withString:@""]; [self.contactArray addObject:contactModel]; } } }
//到這里未知已經(jīng)把手機(jī)號(hào) 姓名跟頭像獲取到了, 接著要做的就是把獲取到的處理了, 一般來(lái)說(shuō)獲取的全部聯(lián)系人的信息并不會(huì)有很長(zhǎng)時(shí)間, 真正的耗時(shí)就是在獲取之后對(duì)數(shù)組進(jìn)行處理的過(guò)程中
- (void)handleArray { //字典把獲取到的數(shù)組分一下組 self.keyContactDic = [NSMutableDictionary dictionary]; self.keyArray = [NSMutableArray array]; for (ContactBookModel *model in self.contactArray) { NSString *lastName; if (![model.name isEqualToString:@""] || model.name == nil) { lastName =[self transform:[model.name substringToIndex:1]]; } NSString *ZIMU = @"^[A-Za-z]"; NSPredicate *regextestA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ZIMU]; BOOL result = [regextestA evaluateWithObject:lastName]; if (!result) { lastName = @"#"; } if (![self.keyArray containsObject:lastName]) { NSMutableArray *array = [NSMutableArray array]; [array addObject:model]; [self.keyContactDic setObject:array forKey:lastName]; [self.keyArray addObject:lastName]; } else { NSMutableArray *array = [self.keyContactDic objectForKey:lastName]; [array addObject:model]; // NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"characterName" ascending:YES]; // array = [NSMutableArray arrayWithArray:[array sortedArrayUsingDescriptors:@[descriptor]]]; } } NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES]; self.keyArray = [NSMutableArray arrayWithArray:[self.keyArray sortedArrayUsingDescriptors:@[descriptor]]] ; self.searchDic = [NSMutableDictionary dictionary]; [self.searchDic addEntriesFromDictionary:self.keyContactDic]; dispatch_async(dispatch_get_main_queue(), ^{ [self.tableView reloadData]; }); NSMutableArray *array1 = [NSMutableArray array]; for (NSString *key in self.keyContactDic) { NSArray *array = self.searchDic[key]; for (id obj in array) { [array1 addObject:obj]; } } }
//判斷中文還是英文
-(BOOL)IsChinese:(NSString *)str { for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i]; if( a > 0x4e00 && a < 0x9fff) { return YES; } } return NO; }
//漢子轉(zhuǎn)換拼音 把漢子轉(zhuǎn)為拼音進(jìn)行排序是我遇到的最大的坑, 因?yàn)檫@個(gè)造成了二三十秒 卡頓 (大概有四千的通訊錄), 最后求助了一個(gè)群里的大神給了一個(gè)c文件
- (NSString *)transform:(NSString *)chinese { if ( chinese == nil || [chinese isEqualToString:@""]) { return nil; }
if ([self IsChinese:chinese]) { char cc = pinyinFirstLetter([chinese characterAtIndex:0]); return [NSString stringWithFormat:@"%c",cc ].uppercaseString; } else { return [chinese substringToIndex:1].uppercaseString; } }
寫(xiě)到這里大概通訊錄的大概就有了, 數(shù)組為全部的, 字典是排過(guò)序的, 接下來(lái)做的就是存入沙盒中, 因?yàn)槲覀儾豢赡苊看味歼^(guò)來(lái)獲取通訊錄, 我們歸檔模型, 存入cache
model的.h中遵守NSCoding 而在.m中實(shí)現(xiàn)
- (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:self.telephone forKey:@"telephone"]; [aCoder encodeObject:self.lastName forKey:@"lastName"]; [aCoder encodeObject:self.characterName forKey:@"characterName"]; [aCoder encodeObject:self.imageData forKey:@"imageData"]; [aCoder encodeBool:self.isSelect forKey:@"isSelect"]; }
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { self.name = [aDecoder decodeObjectForKey:@"name"]; self.telephone = [aDecoder decodeObjectForKey:@"telephone"]; self.lastName = [aDecoder decodeObjectForKey:@"lastName"]; self.characterName = [aDecoder decodeObjectForKey:@"characterName"]; self.imageData = [aDecoder decodeObjectForKey:@"imageData"]; self.isSelect = [aDecoder decodeBoolForKey:@"isSelect"]; } return self; }
//下面寫(xiě)到沙盒中
- (void)writeToSandBox { NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSString *conactPath = [cache stringByAppendingPathComponent:@"contactArray.text"]; BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:conactPath]; if (exist) { BOOL result = [[NSFileManager defaultManager] removeItemAtPath:conactPath error:nil]; if (result) { NSLog(@"移除成功"); } else { NSLog(@"移除失敗"); } }
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //我這里把總的數(shù)組存進(jìn)去了, 因?yàn)槲乙玫闹皇侨康臄?shù)組就行, 如果有需要可以把字典也存進(jìn)去 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.contactArray]; BOOL result = [data writeToFile:conactPath atomically:YES]; if (result) { NSLog(@"寫(xiě)入成功"); }else { NSLog(@"寫(xiě)入失敗"); } }); }
//然后我們可以在用的地方存沙盒中取出來(lái)
//還沒(méi)有完, 因?yàn)槲覀冇脩?hù)會(huì)修改通訊錄的, 不過(guò)不要怕有修改的回調(diào)函數(shù), 我們?cè)赼ppdelegate中寫(xiě)下如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //類(lèi)似于觀察者, 當(dāng)用戶(hù)修改了通訊錄, 我們進(jìn)入程序會(huì)有回調(diào) ABAddressBookRef addresBook = ABAddressBookCreateWithOptions(NULL, NULL); ABAddressBookRegisterExternalChangeCallback(addresBook, addressBookChanged, (__bridge void *)(self)); return YES; }
void addressBookChanged(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) { //這是一個(gè)回調(diào)函數(shù), 當(dāng)通訊錄發(fā)生改變的時(shí)候, 用戶(hù)再次進(jìn)來(lái)會(huì)有回調(diào), 我們可以在這里做操作, 比如重新讀取通訊錄把老的數(shù)據(jù)從沙盒中刪除, 然后把新的寫(xiě)入沙盒 }
//簡(jiǎn)書(shū)寫(xiě)文章排版也是一個(gè)大問(wèn)題, 以后好好學(xué)下也要, 這樣的排版我自己都不愿意看..... 我看看有沒(méi)有上傳文件的地方, 上傳一份最終要的是c文件漢子轉(zhuǎn)拼音的那個(gè)