Developer/iOS

[iOS]iOS9 Contacts 이용해 연락처, 주소록 가져오기

블로blow 2016. 1. 5. 15:53
728x90


1.Build Phases -> Link Binary With Libraries 에서

Contacts.framework 추가하기.


2. 코드 작성

-(void)loadContactList {

    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];

    if( status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted)

    {

        NSLog(@"access denied");

    }

    else

    {

        //Create repository objects contacts

        CNContactStore *contactStore = [[CNContactStore alloc] init];

        

        //Select the contact you want to import the key attribute  ( https://developer.apple.com/library/watchos/documentation/Contacts/Reference/CNContact_Class/index.html#//apple_ref/doc/constant_group/Metadata_Keys )

        

        NSArray *keys = [[NSArray alloc]initWithObjects:CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactImageDataKey, CNContactImageDataAvailableKey, nil];

        

        // Create a request object

        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];

        request.predicate = nil;

        

        NSMutableArray  *contactArray = [[NSMutableArray alloc] init];

        [contactStore enumerateContactsWithFetchRequest:request

                                                  error:nil

                                             usingBlock:^(CNContact* __nonnull contact, BOOL* __nonnull stop)

         {

             // Contact one each function block is executed whenever you get

             NSString *phoneNumber = @"";

             if( contact.phoneNumbers)

                 phoneNumber = [[[contact.phoneNumbers firstObject] value] stringValue];

             

             NSLog(@"phoneNumber = %@", phoneNumber);

             NSLog(@"givenname = %@", contact.givenName);

             NSLog(@"familyname = %@", contact.familyName);

             

             [contactArray addObject:contact];

         }];

    }

}



728x90