检索通讯录,根据输入的电话号码的每一位下拉显示检索结果

首先建一个model类保存电话本信息

.h里面

{
    NSInteger sectionNumber;
    NSInteger recordID;
    NSString *name;
    NSString *email;
    NSString *tel;
}
@property NSInteger sectionNumber;
@property NSInteger recordID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *tel;

 

model.m里面

#import "PhoneBookModel.h"

@implementation PhoneBookModel
@synthesize name, email, tel, recordID, sectionNumber;
@end

在要检索电话本的类里面引入头文件

#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "PhoneBookModel.h"

实现代理方法

@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *totalBookArr;
@property (nonatomic, strong) NSMutableArray *bianliArr;
@property (nonatomic, strong) NSString *textStr;

@property (nonatomic, assign) BOOL isNameSearch;
#pragma mark - getMyPhoneBook
- (void)getMyPhoneBook{
    
    _totalBookArr = [NSMutableArray array];
    _bianliArr = [NSMutableArray array];
    
    self.navigationController.navigationBar.translucent = NO;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchTField.frame), [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(_searchTField.frame) - 64) style:UITableViewStylePlain];
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.bounces = NO;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
    _tableView.hidden = YES;
    
    ABAddressBookRef addressBooks = nil;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        addressBooks = ABAddressBookCreateWithOptions(NULL, NULL);
        
        //获取通讯录权限
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        
        ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error)
                                                 {
                                                     dispatch_semaphore_signal(sema);
                                                 });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
    else
    {
        addressBooks = ABAddressBookCreate();
    }
    //获取通讯录中的所有人
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
    
    //通讯录中人数
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
    
    //循环,获取每个人的个人信息
    for (NSInteger i = 0; i < nPeople; i++)
    {
        
        //初始化model;
        PhoneBookModel *bookModel = [[PhoneBookModel alloc] init];
        
        //获取个人
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
        
        //获取个人名字
        CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
        CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
        CFTypeRef abFullName = ABRecordCopyCompositeName(person);
        NSString *nameString = (__bridge NSString *)abName;
        NSString *lastNameString = (__bridge NSString *)abLastName;
        
        if ((__bridge id)abFullName !=nil)
        {
            nameString = (__bridge NSString *)abFullName;
        }
        else
        {
            if ((__bridge id)abLastName != nil)
            {
                nameString = [NSString stringWithFormat:@"%@ %@",nameString,lastNameString];
            }
        }
        bookModel.name = nameString;
        bookModel.recordID = (int)ABRecordGetRecordID(person);
        
        ABPropertyID multiProperties[] =
        {
            kABPersonPhoneProperty,
            kABPersonEmailProperty
        };
        
        NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
        
        for (NSInteger j = 0; j < multiPropertiesTotal; j ++)
        {
            ABPropertyID property = multiProperties[j];
            ABMultiValueRef valueRef = ABRecordCopyValue(person, property);
            NSInteger valuesCount = 0;
            if (valueRef != nil)
            {
                valuesCount = ABMultiValueGetCount(valueRef);
                
                if (valuesCount == 0)
                {
                    continue;
                }
                //获取电话号码和email
                for (NSInteger k = 0; k < valuesCount; k++)
                {
                    CFTypeRef value = ABMultiValueCopyValueAtIndex(valueRef, k);
                    switch (j)
                    {
                        case 0://PhoneNum
                            bookModel.tel = (__bridge NSString *)value;
                            break;
                        case 1://Email
                            bookModel.email = (__bridge NSString *)value;
                            break;
                        default:
                            break;
                    }
                }
            }
            bookModel.tel = [bookModel.tel stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            //将个人信息添加到数组中
            [_totalBookArr addObject:bookModel];
        }
    }
}

#pragma mark - 根据中文名检索通讯录
- (void)textFiledChanged:(UITextField *)tFiled{
    
    NSLog(@"tFiled.text = %@",tFiled.text);
    
    if (![self isAllNum:tFiled.text])
    {
        
        _isNameSearch = YES;
        
        _tableView.hidden = NO;
        
        _bianliArr = [NSMutableArray array];
        
        for (PhoneBookModel *book in _totalBookArr)
        {
            if ([book.name hasPrefix:tFiled.text])
            {
                [_bianliArr addObject:book];
            }
        }
        [_tableView reloadData];
    }
}
#pragma mark - 根据电话号码检索通讯录
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    _tableView.hidden = NO;
    
    _bianliArr = [NSMutableArray array];
    
    NSString *str = [textField.text stringByAppendingString:string];//字符串拼接
    
    if (range.length == 1)
    {
        str = [str substringToIndex:range.location];
    }
    
    NSLog(@"str = %@",str);
    
    _textStr = str;
    
    if ([self isAllNum:str]) {
        
        _isNameSearch = NO;
        
        if (str.length == 0)
        {
            _tableView.hidden = YES;
            
        }else
        {
            for (PhoneBookModel *book in _totalBookArr)
            {
                if ([book.tel hasPrefix:str])
                {
                    [_bianliArr addObject:book];
                }
                
            }
            [_tableView reloadData];
        }
    }
    return YES;
}
- (BOOL)isAllNum:(NSString *)string{
    unichar c;
    for (int i=0; i<string.length; i++) {
        c=[string characterAtIndex:i];
        if (!isdigit(c)) {
            return NO;
        }
    }
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_searchTField resignFirstResponder];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _bianliArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellIdentifier = @"ContactCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    PhoneBookModel *book = [_bianliArr objectAtIndex:indexPath.row];
    
    cell.textLabel.text = book.name;
    
    if (_isNameSearch) {
        
        cell.detailTextLabel.text = book.tel;
    }else{
        
        NSInteger length = _textStr.length;
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:book.tel];
        
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,length)];
        
        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:17.0] range:NSMakeRange(0,length)];
        
        cell.detailTextLabel.attributedText = str;
    }
    return cell;
}

 

这样就可以根据你每一次输入的电话号码检索与之匹配的号码;

 

posted @ 2015-11-17 14:25  Mr_tao  阅读(408)  评论(0编辑  收藏  举报