ContactVC.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //
  2. // ContactVC.m
  3. // 通讯录
  4. //
  5. // Created by EchoShacolee on 2017/5/22.
  6. // Copyright © 2017年 lee. All rights reserved.
  7. //
  8. #import "ContactVC.h"
  9. #import <Contacts/Contacts.h>
  10. #import "ChineseToPinyin.h"
  11. #import "ContactDetailVC.h"
  12. #import "ContactResultVC.h"
  13. @interface ContactVC ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate>
  14. {
  15. //基本数据
  16. NSMutableArray * _detailData;
  17. NSMutableArray * _sectionTitles; // 每个分区的标题
  18. NSMutableArray * _AllNullData;
  19. NSMutableArray * _AllZiMu;
  20. UITableView * _tableview;
  21. //搜索相关
  22. NSMutableArray * _resultArr;
  23. NSMutableArray * _allUser;//不分组的所有数据
  24. ContactResultVC * _resultVC;
  25. }
  26. @property(nonatomic,strong)UISearchController * searchController;
  27. @property(nonatomic,strong)UILabel * lab;//为打开通讯录提示
  28. @end
  29. @implementation ContactVC
  30. - (void)viewDidLoad {
  31. [super viewDidLoad];
  32. self.navigationItem.title = @"通讯录";
  33. self.view.backgroundColor = KBackGroundColor;
  34. _detailData = [NSMutableArray new];
  35. _sectionTitles = [NSMutableArray new];
  36. _AllNullData = [NSMutableArray new];
  37. _AllZiMu = [NSMutableArray new];
  38. _resultArr = [NSMutableArray new];
  39. _allUser = [NSMutableArray new];
  40. for(char c ='A';c<='Z';c++){
  41. //当前字母
  42. NSString *zimu=[NSString stringWithFormat:@"%c",c];
  43. [_AllZiMu addObject:zimu];
  44. [_AllNullData addObject:[NSMutableArray new]];
  45. }
  46. [_AllZiMu addObject:@"#"];
  47. [_AllNullData addObject:[NSMutableArray new]];
  48. [self requestAuthorizationForAddressBook];//判断是否(每次改变权限,会导致app重启,都会经过这里)
  49. }
  50. -(void)viewDidAppear:(BOOL)animated {
  51. [super viewDidAppear:animated];
  52. self.tabBarController.tabBar.hidden = NO;
  53. }
  54. #pragma mark 通讯录相关
  55. - (void)requestAuthorizationForAddressBook{
  56. CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
  57. //如果用户未做决定
  58. if (authorizationStatus == CNAuthorizationStatusNotDetermined) {
  59. CNContactStore *contactStore = [[CNContactStore alloc] init];
  60. [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
  61. if (granted) {
  62. [self getData];
  63. } else {
  64. //用户拒绝
  65. dispatch_async(dispatch_get_main_queue(), ^{
  66. [self.view addSubview:self.lab];
  67. });
  68. }
  69. }];
  70. }else if (authorizationStatus != CNAuthorizationStatusAuthorized){
  71. //用户拒绝 或者 app无权限
  72. if (_tableview) {//测试的时候每次改变权限都会重启app,所以这个判断似乎没必要
  73. [_tableview removeFromSuperview];
  74. }
  75. dispatch_async(dispatch_get_main_queue(), ^{
  76. [self.view addSubview:self.lab];
  77. });
  78. }else{
  79. [self getData];
  80. }
  81. }
  82. -(void)getData{
  83. // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
  84. NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
  85. CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
  86. CNContactStore *contactStore = [[CNContactStore alloc] init];
  87. [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
  88. // NSLog(@"-------------------------------------------------------%@",contact);
  89. NSString *givenName = contact.givenName;
  90. NSString *familyName = contact.familyName;
  91. NSString * name = [NSString stringWithFormat:@"%@%@",familyName,givenName];
  92. NSString * first = [NSString stringWithFormat:@"%c",[ChineseToPinyin sortSectionTitle:name]];
  93. NSMutableArray * mArr = [NSMutableArray new];
  94. if (name.length == 0) {
  95. name = @"<未命名>";
  96. }
  97. [mArr addObject:name];
  98. NSArray *phoneNumbers = contact.phoneNumbers;
  99. for (CNLabeledValue *labelValue in phoneNumbers) {
  100. NSString *label = labelValue.label;
  101. CNPhoneNumber *phoneNumber = labelValue.value;
  102. // NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);
  103. if (label == nil) {
  104. label = @"电话";
  105. }else if([label isEqualToString:@"_$!<Mobile>!$_"]){
  106. label = @"手机";
  107. }else if([label isEqualToString:@"_$!<Home>!$_"]){
  108. label = @"家用";
  109. }else if([label isEqualToString:@"_$!<Work>!$_"]){
  110. label = @"工作";
  111. }
  112. [mArr addObject:@{phoneNumber.stringValue:label}];
  113. }
  114. [_allUser addObject:mArr];
  115. if ([_AllZiMu containsObject:first]) {
  116. NSInteger index = [_AllZiMu indexOfObject:first];
  117. [_AllNullData[index] addObject:mArr];
  118. }
  119. }];
  120. int i=0;
  121. for (NSArray *arr in _AllNullData) {
  122. if (arr.count != 0) {
  123. [_detailData addObject:arr];
  124. [_sectionTitles addObject:_AllZiMu[i]];
  125. }
  126. i++;
  127. }
  128. dispatch_async(dispatch_get_main_queue(), ^{
  129. [self createTableView];
  130. });
  131. }
  132. -(void)createTableView{
  133. if (_lab) {
  134. [_lab removeFromSuperview];
  135. }
  136. self.navigationController.navigationBar.translucent = NO;
  137. self.definesPresentationContext = YES;//解决激活的时候消失的问题
  138. _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, kSize.width, kSize.height-kNavOffSet-kTabBarHeight-44) style:0];
  139. _tableview.delegate = self;
  140. _tableview.dataSource = self;
  141. _tableview.showsVerticalScrollIndicator = NO;
  142. _tableview.tableFooterView = [UIView new];
  143. _tableview.sectionIndexColor = RQMianColor;
  144. _resultVC = [[ContactResultVC alloc]init];
  145. __weak typeof(self) weakSelf = self;
  146. _resultVC.pushBlock = ^(NSMutableArray *arr) {
  147. ContactDetailVC * vc = [[ContactDetailVC alloc]init];
  148. vc.oneDetail = arr;
  149. [weakSelf navPushHideTabbarToVC:vc];
  150. };
  151. _searchController = [[UISearchController alloc]initWithSearchResultsController:_resultVC];
  152. [_searchController loadViewIfNeeded];//解决报错**Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UISearchController: 0x7f9c28c9d740>)**
  153. _searchController.delegate = self;
  154. _searchController.searchResultsUpdater = self;
  155. //搜索时,背景变暗色(感受不到区别)
  156. _searchController.dimsBackgroundDuringPresentation = YES;
  157. //搜索时,背景变模糊(模糊我感受不到,但是当前vc点击被屏蔽)
  158. _searchController.obscuresBackgroundDuringPresentation = YES;
  159. //搜索时,隐藏导航栏
  160. _searchController.hidesNavigationBarDuringPresentation = YES;
  161. _searchController.searchBar.frame = CGRectMake(0, 0, _searchController.searchBar.frame.size.width, 44.0);
  162. _searchController.searchBar.placeholder = @"搜索";
  163. _searchController.searchBar.tintColor = RQMianColor;
  164. _searchController.searchBar.delegate = self;
  165. [self.view addSubview:_tableview];
  166. [self.view addSubview:_searchController.searchBar];
  167. _resultVC.scrollBlock = ^{
  168. [weakSelf.searchController.searchBar resignFirstResponder];
  169. };
  170. }
  171. -(UILabel *)lab{
  172. if (!_lab) {
  173. _lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kSize.width, 90)];
  174. _lab.center = self.view.center;//CGPointMake(self.view.center.x, self.view.center.y-knavOffset-100)
  175. _lab.text = @"未打开通讯录授权\n(打开方式:设置-隐私-通讯录-极速驾培)";
  176. _lab.textAlignment = NSTextAlignmentCenter;
  177. _lab.numberOfLines = 0;
  178. _lab.textColor =[UIColor lightGrayColor];
  179. }
  180. return _lab;
  181. }
  182. #pragma mark searchcontroller代理
  183. -(void)willPresentSearchController:(UISearchController *)searchController{
  184. _searchController.searchBar.showsCancelButton = YES;
  185. UIButton *canceLBtn = [_searchController.searchBar valueForKey:@"cancelButton"];
  186. [canceLBtn setTitle:@"取消" forState:UIControlStateNormal];
  187. [canceLBtn setTitleColor:RQMianColor forState:UIControlStateNormal];
  188. }
  189. -(void)didDismissSearchController:(UISearchController *)searchController{
  190. _searchController.searchBar.frame = CGRectMake(0, 0, _searchController.searchBar.frame.size.width, 44.0);
  191. }
  192. #pragma mark UISearchResultsUpdating代理
  193. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
  194. NSString *searchString = [searchController.searchBar text];
  195. if (_resultArr != nil) {
  196. [_resultArr removeAllObjects];
  197. }
  198. //过滤数据
  199. for (NSArray *arr in _allUser) {
  200. if ([arr[0] containsString:searchString]) {
  201. [_resultArr addObject:arr];
  202. }
  203. }
  204. //刷新表格
  205. _resultVC.dataSource = _resultArr;
  206. if (_resultVC.reloadBlock) {
  207. _resultVC.reloadBlock();
  208. }
  209. }
  210. #pragma mark searchbar代理
  211. - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  212. [searchBar resignFirstResponder];
  213. }
  214. #pragma mark tableview代理相关
  215. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  216. return [_detailData count];
  217. }
  218. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  219. return [_detailData[section] count];
  220. }
  221. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
  222. UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSize.width-15, 28)];
  223. view.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1];
  224. UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, kSize.width-15, 28)];
  225. lable.text = [NSString stringWithFormat:@"%@",_sectionTitles[section]];
  226. lable.font = [UIFont boldSystemFontOfSize:17];
  227. [view addSubview:lable];
  228. return view;
  229. }
  230. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  231. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
  232. if (!cell) {
  233. cell = [[UITableViewCell alloc]initWithStyle:0 reuseIdentifier:@"cellID"];
  234. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  235. }
  236. cell.textLabel.text = _detailData[indexPath.section][indexPath.row][0];
  237. return cell;
  238. }
  239. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  240. ContactDetailVC * vc = [[ContactDetailVC alloc]init];
  241. vc.oneDetail = _detailData[indexPath.section][indexPath.row];
  242. [self navPushHideTabbarToVC:vc];
  243. }
  244. #pragma mark 索引相关
  245. // 每个分区的页眉
  246. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  247. {
  248. return [_sectionTitles objectAtIndex:section];
  249. }
  250. // 索引目录
  251. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  252. {
  253. return _sectionTitles;
  254. }
  255. // 点击目录(响应索引点击)
  256. -(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  257. {
  258. // 获取所点目录对应的indexPath值
  259. NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:index];
  260. // 让table滚动到对应的indexPath位置
  261. [tableView scrollToRowAtIndexPath:selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
  262. return index;
  263. }
  264. - (void)didReceiveMemoryWarning {
  265. [super didReceiveMemoryWarning];
  266. // Dispose of any resources that can be recreated.
  267. }
  268. @end