iOS读取本地通讯录示例代码:

iOS读取本地通讯录示例代码:

+ (NSArray *)readAllPeoples
{
    ABAddressBookRef tmpAddressBook = nil;
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        tmpAddressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(tmpAddressBook, ^(bool greanted, CFErrorRef error){
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    } else {
        tmpAddressBook = ABAddressBookCreate();
    }
 
    if (!tmpAddressBook) {
        return nil;
    }
    
    NSArray *tmpPeoples = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(tmpAddressBook);
    for(id tmpPerson in tmpPeoples){
        NSString *userName = @"";
        
        NSString *firstName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonFirstNameProperty);
        NSString *lastName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonLastNameProperty);
        
     if ([NSString isVaildString:firstName] && [NSString isVaildString:lastName]) {
            userName = [NSString stringWithFormat:@"%@%@",lastName,firstName];

        }else if([NSString isVaildString:firstName]){
            userName = [NSString stringWithFormat:@"%@",firstName];
        }else if([NSString isVaildString:lastName]){
            userName = [NSString stringWithFormat:@"%@",lastName];
        }
        
        ABMultiValueRef tmpPhones = ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonPhoneProperty);
        NSInteger photoCount = ABMultiValueGetCount(tmpPhones);
        if (photoCount < 5) {
            for(NSInteger j = 0; j < photoCount; j++){
                NSString *tmpPhoneStr = (__bridge NSString*)ABMultiValueCopyValueAtIndex(tmpPhones, j);
                ITTDINFO(@"telPhone:%@",tmpPhoneStr);
                NSString *telPhone = [tmpPhoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
                if ([CommonUtils checkPhoneNumInput:telPhone]) {
                    AddressBookModel *model = [[AddressBookModel alloc] init];
                    model.userName = userName;
                    model.telPhone = telPhone;
                    [array addObject:model];
                }
            }
        }
        CFRelease(tmpPhones);
    }
    
    CFRelease(tmpAddressBook);
    
    return array;
}


+ (BOOL)checkPhoneNumInput:(NSString *)telePhone

{

    NSString *MOBILE = @"^1[34578][0-9]{9}$";

   NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];

   return [regextestmobile evaluateWithObject:telePhone];

}



原文地址:https://www.cnblogs.com/tomblogblog/p/4201211.html