如何访问Objective C中的PhoneBook Contacts?

时间:2017-04-04 09:30:44

标签: objective-c

我想向我的TableView显示电话簿详细信息,例如联系人姓名和手机号码。如何访问电话簿详细信息。 在Objective C中我想要的所有这些。

谢谢

2 个答案:

答案 0 :(得分:0)

从构建阶段添加框架

#import <AddressBook/ABAddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

添加nsobject的新文件

@property (nonatomic , strong) NSString *firstName;
@property (nonatomic , strong) NSString *phNumber;

@property (strong, nonatomic) UIImage *imgUser;

<强> viewController.m

- (void)viewDidLoad {
[super viewDidLoad];
[self contactScan];
}

- (void) contactScan
{
if ([CNContactStore class]) {
    //ios9 or later
    FirstGlobalContactList =[[NSMutableArray alloc]init];
    GlobalContactList = [[NSMutableArray alloc] init];
    Mobiarray =[[NSMutableArray alloc]init];
    nameArray =[[NSMutableArray alloc]init];
    imageArray =[[NSMutableArray alloc]init];
    CNEntityType entityType = CNEntityTypeContacts;
    if( [CNContactStore authorizationStatusForEntityType:entityType] == CNAuthorizationStatusNotDetermined)
    {
        CNContactStore * contactStore = [[CNContactStore alloc] init];
        [contactStore requestAccessForEntityType:entityType completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if(granted){
                [self getAllContact];
            }
        }];
    }
    else if( [CNContactStore authorizationStatusForEntityType:entityType]== CNAuthorizationStatusAuthorized)
    {
        [self getAllContact];
    }
}
}

-(void)getAllContact
{
if([CNContactStore class])
{
    //iOS 9 or later
    NSError* contactError;

    CNContactStore* addressBook = [[CNContactStore alloc]init];
    [addressBook containersMatchingPredicate:[CNContainer predicateForContainersWithIdentifiers: @[addressBook.defaultContainerIdentifier]] error:&contactError];
    NSArray * keysToFetch =@[CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPostalAddressesKey,CNContactImageDataKey];
    CNContactFetchRequest * request = [[CNContactFetchRequest alloc]initWithKeysToFetch:keysToFetch];
    contacts = [NSMutableArray array];
    BOOL success = [addressBook enumerateContactsWithFetchRequest:request error:&contactError usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop)

                    {
                        [contacts addObject:contact];


                    }];
    [self parseContactWithContact];

}
}

- (void)parseContactWithContact
{
NSLog(@"contacts count---->%ld",(unsigned long)[contacts count]);
for (NSInteger i=0; i<[contacts count]; i++)
{


    CNContact *contact =[contacts objectAtIndex:i];
    Person *obj = [[Person alloc]init];

    NSString * firstName =  contact.givenName;
    NSString * lastName =  contact.familyName;


    NSArray * phone = [[contact.phoneNumbers valueForKey:@"value"] valueForKey:@"digits"];
    //  NSString * email = [contact.emailAddresses valueForKey:@"value"];
    NSString *phoneNumber;
    if ([phone count]==0)
    {
        phoneNumber =@"(null)";
    }
    else
    {
        phoneNumber =[phone objectAtIndex:0];
        NSLog(@"phoneNumber----->%@",phoneNumber);
    }

    if (phoneNumber == (id)[NSNull null] || phoneNumber.length == 0 ||[phoneNumber isEqualToString:@"(null)"])

    {
        NSLog(@"no phone number");

    }
    else if (firstName == (id)[NSNull null]|| firstName.length == 0 ||[firstName isEqualToString:@"(null)"])
    {
        NSLog(@"no name ");
    }
    else
    {
        NSString *strname = [firstName stringByAppendingString:[NSString stringWithFormat:@" %@",lastName]];
        NSLog(@"str name ---->%@",strname);
        NSLog(@"stphone number is ---->%@",phoneNumber);


        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^a-zA-Z0-9]*$" options:0 error:NULL];
        NSString *string = phoneNumber;
        NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];


        NSString *removeparentdis = [[modifiedString stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];

        NSString*str=  [removeparentdis stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *newstr = [trimmed stringByReplacingOccurrencesOfString:@" " withString:@""];

        NSString *str2 =newstr;
        NSString * strippedNumber = [str2 stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [str2 length])];

        CNContact *contact =[contacts objectAtIndex:i];
        NSData *data =contact.imageData;
        UIImage *image = [UIImage imageWithData:data];

        if (image)
        {
              NSLog(@"check image exit");
            obj.phNumber = strippedNumber;
            obj.firstName=strname;
            obj.imgUser =image;
            [FirstGlobalContactList addObject:obj];
                      }
        else
        {
            image = [UIImage imageNamed:@"user"];
              NSLog(@"no image exit");
            obj.phNumber = strippedNumber;
            obj.firstName=strname;
            obj.imgUser =image;
            [FirstGlobalContactList addObject:obj];
        }
    }
}
for (int i=0; i<[FirstGlobalContactList count]; i++)
{
    Person *per =[FirstGlobalContactList objectAtIndex:i];
    NSString *namestr = per.firstName;
    NSString *phonestr =per.phNumber;
    UIImage *img =per.imgUser;

    [Mobiarray addObject:phonestr];
    [nameArray addObject:namestr];
    [imageArray addObject:img];
}

NSArray *copy = [Mobiarray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator])
{
    if ([Mobiarray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [Mobiarray removeObjectAtIndex:index];
        [nameArray removeObjectAtIndex:index];
        [imageArray removeObjectAtIndex:index];
        // NSLog(@"index value is ====>%ld",(long)index);
    }
    index--;
}
for (NSInteger i=0; i<[Mobiarray count]; i++)
{
    Person *obj =[[Person alloc]init];
    obj.phNumber = [NSString stringWithFormat:@"%@",[Mobiarray objectAtIndex:i]];
    obj.firstName =[NSString stringWithFormat:@"%@",[nameArray objectAtIndex:i]];
    obj.imgUser =[imageArray objectAtIndex:i];
    // NSLog(@"obj first name is ===>%@",obj.phNumber);
    // NSLog(@"phone number is ====>%@",obj.firstName);
    [GlobalContactList addObject:obj];
}

contactList =[[NSMutableArray alloc]init];
for (NSInteger i=0; i<[GlobalContactList count]; i++)
{
    Person *person = [GlobalContactList objectAtIndex:i];


    NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
    [dict setObject:person.firstName forKey:@"name"];
    [dict setObject:person.phNumber forKey:@"Phone"];
    [dict setObject:person.imgUser forKey:@"Image"];

    [contactList addObject:dict];
}
}

借助此代码,您可以获取该用户的所有名称,电子邮件,地址,照片等等

答案 1 :(得分:0)

AddressBook AddressBookUI 已弃用

@import Contacts; 
@import ContactsUI;

#import <Contacts/Contacts.h>
#import <Contacts/ContactsUI.h>

从设备

获取所有联系人
-(void)fetchAllContactsCompletionHandler:(void(^)(BOOL granted, NSError * _Nullable error))completion
{
    self.contactArray = [[NSMutableArray alloc] init];

    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        if (granted)
        {
            NSArray *keys = @[CNContactNamePrefixKey, CNContactFamilyNameKey, CNContactGivenNameKey,
                              CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey];

            NSString *containerId = store.defaultContainerIdentifier;
            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
            NSError *error;
            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];

            if (error)
            {
                NSLog(@"ERROR IN FETCHING CONTACTS :: %@", error.description);
            }
            else
            {
                for (CNContact *contact in cnContacts)
                {
                    @try
                    {
                        CMCustomContacts *newContact = [[CMCustomContacts alloc] init];
                        newContact.phoneArray = [[NSMutableArray alloc] init];
                        newContact.emailArray = [[NSMutableArray alloc] init];

                        newContact.firstName = contact.givenName;
                        newContact.lastName = contact.familyName;

                        UIImage *image = [UIImage imageWithData:contact.imageData];
                        newContact.profileImage = image;

                        for (CNLabeledValue *label in contact.phoneNumbers)
                        {
                            NSString *phone = [label.value stringValue];
                            if ([phone length] > 0)
                            {
                                [newContact.phoneArray addObject:phone]; NSLog(@"PHONE :: %@",phone);
                            }
                        }

                        for (CNLabeledValue *label in contact.emailAddresses)
                        {
                            NSString *email = label.value;
                            if ([email length] > 0)
                            {
                                [newContact.emailArray addObject:email];  NSLog(@"EMAIL :: %@",email);
                            }
                        }

                        [self.contactArray addObject:newContact];
                    }
                    @catch (NSException *exception)
                    {
                        NSLog(@"EXCEPTION IN CONTACTS :: %@", exception.description);
                    }
                    @finally
                    {
                        NSLog(@"FINALLY");
                    }
                }

                NSLog(@"COUNT OF CONTACTS :: %lu", (unsigned long)self.contactArray.count);
            }
        }
        completion(granted, error);
    }];

如果需要直接从设备联系人中选择联系人:您可以使用此链接

https://medium.com/@abhishekthaplithapliyal/contacts-ui-contacts-framework-and-create-vcard-vcf-in-objective-c-51b73e7f7d93