2016-08-21 1 views
0

이름과 전화 번호부에 액세스하려고 시도하면서 며칠 동안 고통을 겪고 있습니다. 모두 실패했습니다. 테스트 응용 프로그램에서 성공적으로 작동하는 다음 코드를 사용하지만 프로젝트 작업에 추가하면 작동하지 않습니다. 변수 "granted"는 값이 "false"이고 오류 "Access Failure"가 발생합니다. 그럼에도 불구하고, 개인 정보 보호 설정에서 ... 액세스 나는 오히려 이상한 행동에 대한 답을 찾을 수 없습니다 오랫동안이 을 ... 수 있도록 슬라이더를 표시되지 않습니다 응용 프로그램에서 전화 번호부에 액세스 할 수 없습니다.

내가 어떤 도움을 감사하게 될 것입니다!`

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

     NSMutableArray *contacts = [NSMutableArray array]; 

     NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey]; 
     NSString *containerId = store.defaultContainerIdentifier; 
     NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId]; 
     NSError *error; 
     NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error]; 
     if (error) { 
      NSLog(@"error fetching contacts %@", error); 
     } else { 
      for (CNContact *contact in cnContacts) { 

       TSContact *newContact = [[TSContact alloc] init]; 
       newContact.firstName = contact.givenName; 
       newContact.lastName = contact.familyName; 
       UIImage *image = [UIImage imageWithData:contact.imageData]; 
       newContact.image = image; 
       for (CNLabeledValue *label in contact.phoneNumbers) { 
        NSString *phone = [label.value stringValue]; 
        if ([phone length] > 0) { 
         [contacts addObject:phone]; 
        } 
       } 
      } 
     } 
    } else { 
     NSLog(@"Error = %@", error.localizedDescription); 
    } 
}]; 
+0

앱의 배포 대상은 무엇입니까 (iOS 버전 6.0을 타겟팅합니까)? – theFool

+0

info.plist에'Privacy - Contacts Usage Description' 키를 추가 했습니까? iOS 6.0 이상에서 지원됩니다. –

+0

iOS 8과 9가 여전히 작동하지 않습니다. –

답변

0

당신이 다음 주소록에있는 기존 연락처의 정보에 액세스하려면 코드는

1 단계을 :) 도움이 될 수 추가

#import <AddressBook/AddressBook.h> 

2 단계 : 3 단계

-(void)phonenumber { self.navigationController.navigationBarHidden = true; ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus(); if (status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted) { // if you got here, user had previously denied/revoked permission for your // app to access the contacts, and all you can do is handle this gracefully, // perhaps telling the user that they have to go to settings to grant access // to contacts [[[UIAlertView alloc] initWithTitle:nil message:@"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; return; } CFErrorRef error = NULL; ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); if (!addressBook) { NSLog(@"ABAddressBookCreateWithOptions error: %@", CFBridgingRelease(error)); return; } ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { if (error) { NSLog(@"ABAddressBookRequestAccessWithCompletion error: %@", CFBridgingRelease(error)); } if (granted) { // if they gave you permission, then just carry on [self listPeopleInAddressBook:addressBook]; } else { // however, if they didn't give you permission, handle it gracefully, for example... dispatch_async(dispatch_get_main_queue(), ^{ // BTW, this is not on the main thread, so dispatch UI updates back to the main queue [[[UIAlertView alloc] initWithTitle:nil message:@"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; }); } CFRelease(addressBook); }); // Do any additional setup after loading the view. } 

의 viewDidLoad

에서 방법을 다음 호출 :
이 방법은 당신에게 특정 연락처에 필요한 모든 정보를 제공합니다 코드 에도이 방법을 추가합니다.

- (void)listPeopleInAddressBook:(ABAddressBookRef)addressBook 
{ 
      //Run UI Updates 
      NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook)); 
      NSInteger numberOfPeople = [allPeople count]; 

      for (NSInteger i = 0; i < numberOfPeople; i++) { 
       ABRecordRef person = (__bridge ABRecordRef)allPeople[i]; 
       //From Below code you can get what you want. 
       NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty)); 
       NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty)); 
       NSLog(@"Name:%@ %@", firstName, lastName); 

       ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty); 
       NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, 0)); 
       NSLog(@"phone:%@", phoneNumber); 
       NSLog(@"============================================="); 
      } 

} 
+0

내 응용 프로그램에 코드를 추가했는데, 안타깝게도 응용 프로그램이 시작될 때마다 액세스 경고가 표시됩니다. 연락처에 대한 액세스 설정 및 슬라이더가 표시되지 않는 경우 :( –

+0

내 코드에서 원하는 것을 얻었습니까? 직면 한 문제가 정확히 무엇인지 알 수 없습니까? @ СашаЦвигун –

+0

아니요, 귀하의 코드에서 연락을받지 못했습니다 .. 내 응용 프로그램에 액세스 할 수 없습니다. 개인 정보 설정, 액세스를 허용하는 스위치가 없습니다 ... –