// // ContactVC.m // 通讯录 // // Created by EchoShacolee on 2017/5/22. // Copyright © 2017年 lee. All rights reserved. // #import "ContactVC.h" #import #import "ChineseToPinyin.h" #import "ContactDetailVC.h" #import "ContactResultVC.h" @interface ContactVC () { //基本数据 NSMutableArray * _detailData; NSMutableArray * _sectionTitles; // 每个分区的标题 NSMutableArray * _AllNullData; NSMutableArray * _AllZiMu; UITableView * _tableview; //搜索相关 NSMutableArray * _resultArr; NSMutableArray * _allUser;//不分组的所有数据 ContactResultVC * _resultVC; } @property(nonatomic,strong)UISearchController * searchController; @property(nonatomic,strong)UILabel * lab;//为打开通讯录提示 @end @implementation ContactVC - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = @"通讯录"; self.view.backgroundColor = KBackGroundColor; _detailData = [NSMutableArray new]; _sectionTitles = [NSMutableArray new]; _AllNullData = [NSMutableArray new]; _AllZiMu = [NSMutableArray new]; _resultArr = [NSMutableArray new]; _allUser = [NSMutableArray new]; for(char c ='A';c<='Z';c++){ //当前字母 NSString *zimu=[NSString stringWithFormat:@"%c",c]; [_AllZiMu addObject:zimu]; [_AllNullData addObject:[NSMutableArray new]]; } [_AllZiMu addObject:@"#"]; [_AllNullData addObject:[NSMutableArray new]]; [self requestAuthorizationForAddressBook];//判断是否(每次改变权限,会导致app重启,都会经过这里) } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; self.tabBarController.tabBar.hidden = NO; } #pragma mark 通讯录相关 - (void)requestAuthorizationForAddressBook{ CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; //如果用户未做决定 if (authorizationStatus == CNAuthorizationStatusNotDetermined) { CNContactStore *contactStore = [[CNContactStore alloc] init]; [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { [self getData]; } else { //用户拒绝 dispatch_async(dispatch_get_main_queue(), ^{ [self.view addSubview:self.lab]; }); } }]; }else if (authorizationStatus != CNAuthorizationStatusAuthorized){ //用户拒绝 或者 app无权限 if (_tableview) {//测试的时候每次改变权限都会重启app,所以这个判断似乎没必要 [_tableview removeFromSuperview]; } dispatch_async(dispatch_get_main_queue(), ^{ [self.view addSubview:self.lab]; }); }else{ [self getData]; } } -(void)getData{ // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段 NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]; CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch]; CNContactStore *contactStore = [[CNContactStore alloc] init]; [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) { // NSLog(@"-------------------------------------------------------%@",contact); NSString *givenName = contact.givenName; NSString *familyName = contact.familyName; NSString * name = [NSString stringWithFormat:@"%@%@",familyName,givenName]; NSString * first = [NSString stringWithFormat:@"%c",[ChineseToPinyin sortSectionTitle:name]]; NSMutableArray * mArr = [NSMutableArray new]; if (name.length == 0) { name = @"<未命名>"; } [mArr addObject:name]; NSArray *phoneNumbers = contact.phoneNumbers; for (CNLabeledValue *labelValue in phoneNumbers) { NSString *label = labelValue.label; CNPhoneNumber *phoneNumber = labelValue.value; // NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue); if (label == nil) { label = @"电话"; }else if([label isEqualToString:@"_$!!$_"]){ label = @"手机"; }else if([label isEqualToString:@"_$!!$_"]){ label = @"家用"; }else if([label isEqualToString:@"_$!!$_"]){ label = @"工作"; } [mArr addObject:@{phoneNumber.stringValue:label}]; } [_allUser addObject:mArr]; if ([_AllZiMu containsObject:first]) { NSInteger index = [_AllZiMu indexOfObject:first]; [_AllNullData[index] addObject:mArr]; } }]; int i=0; for (NSArray *arr in _AllNullData) { if (arr.count != 0) { [_detailData addObject:arr]; [_sectionTitles addObject:_AllZiMu[i]]; } i++; } dispatch_async(dispatch_get_main_queue(), ^{ [self createTableView]; }); } -(void)createTableView{ if (_lab) { [_lab removeFromSuperview]; } self.navigationController.navigationBar.translucent = NO; self.definesPresentationContext = YES;//解决激活的时候消失的问题 _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, kSize.width, kSize.height-kNavOffSet-kTabBarHeight-44) style:0]; _tableview.delegate = self; _tableview.dataSource = self; _tableview.showsVerticalScrollIndicator = NO; _tableview.tableFooterView = [UIView new]; _tableview.sectionIndexColor = RQMianColor; _resultVC = [[ContactResultVC alloc]init]; __weak typeof(self) weakSelf = self; _resultVC.pushBlock = ^(NSMutableArray *arr) { ContactDetailVC * vc = [[ContactDetailVC alloc]init]; vc.oneDetail = arr; [weakSelf navPushHideTabbarToVC:vc]; }; _searchController = [[UISearchController alloc]initWithSearchResultsController:_resultVC]; [_searchController loadViewIfNeeded];//解决报错**Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior ()** _searchController.delegate = self; _searchController.searchResultsUpdater = self; //搜索时,背景变暗色(感受不到区别) _searchController.dimsBackgroundDuringPresentation = YES; //搜索时,背景变模糊(模糊我感受不到,但是当前vc点击被屏蔽) _searchController.obscuresBackgroundDuringPresentation = YES; //搜索时,隐藏导航栏 _searchController.hidesNavigationBarDuringPresentation = YES; _searchController.searchBar.frame = CGRectMake(0, 0, _searchController.searchBar.frame.size.width, 44.0); _searchController.searchBar.placeholder = @"搜索"; _searchController.searchBar.tintColor = RQMianColor; _searchController.searchBar.delegate = self; [self.view addSubview:_tableview]; [self.view addSubview:_searchController.searchBar]; _resultVC.scrollBlock = ^{ [weakSelf.searchController.searchBar resignFirstResponder]; }; } -(UILabel *)lab{ if (!_lab) { _lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kSize.width, 90)]; _lab.center = self.view.center;//CGPointMake(self.view.center.x, self.view.center.y-knavOffset-100) _lab.text = @"未打开通讯录授权\n(打开方式:设置-隐私-通讯录-极速驾培)"; _lab.textAlignment = NSTextAlignmentCenter; _lab.numberOfLines = 0; _lab.textColor =[UIColor lightGrayColor]; } return _lab; } #pragma mark searchcontroller代理 -(void)willPresentSearchController:(UISearchController *)searchController{ _searchController.searchBar.showsCancelButton = YES; UIButton *canceLBtn = [_searchController.searchBar valueForKey:@"cancelButton"]; [canceLBtn setTitle:@"取消" forState:UIControlStateNormal]; [canceLBtn setTitleColor:RQMianColor forState:UIControlStateNormal]; } -(void)didDismissSearchController:(UISearchController *)searchController{ _searchController.searchBar.frame = CGRectMake(0, 0, _searchController.searchBar.frame.size.width, 44.0); } #pragma mark UISearchResultsUpdating代理 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController{ NSString *searchString = [searchController.searchBar text]; if (_resultArr != nil) { [_resultArr removeAllObjects]; } //过滤数据 for (NSArray *arr in _allUser) { if ([arr[0] containsString:searchString]) { [_resultArr addObject:arr]; } } //刷新表格 _resultVC.dataSource = _resultArr; if (_resultVC.reloadBlock) { _resultVC.reloadBlock(); } } #pragma mark searchbar代理 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ [searchBar resignFirstResponder]; } #pragma mark tableview代理相关 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return [_detailData count]; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [_detailData[section] count]; } -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSize.width-15, 28)]; view.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1]; UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, kSize.width-15, 28)]; lable.text = [NSString stringWithFormat:@"%@",_sectionTitles[section]]; lable.font = [UIFont boldSystemFontOfSize:17]; [view addSubview:lable]; return view; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"]; if (!cell) { cell = [[UITableViewCell alloc]initWithStyle:0 reuseIdentifier:@"cellID"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } cell.textLabel.text = _detailData[indexPath.section][indexPath.row][0]; return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ ContactDetailVC * vc = [[ContactDetailVC alloc]init]; vc.oneDetail = _detailData[indexPath.section][indexPath.row]; [self navPushHideTabbarToVC:vc]; } #pragma mark 索引相关 // 每个分区的页眉 -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [_sectionTitles objectAtIndex:section]; } // 索引目录 -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return _sectionTitles; } // 点击目录(响应索引点击) -(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { // 获取所点目录对应的indexPath值 NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:index]; // 让table滚动到对应的indexPath位置 [tableView scrollToRowAtIndexPath:selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; return index; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end