2016-08-21 3 views
0

Я страдаю в течение нескольких дней, пытаясь получить доступ к телефонной книге имен и номеров, и все не удалось. Я использую следующий код, который успешно работает в тестовом приложении, но когда я добавляю его в работу над проектом, он не работает. Постоянная переменная «предоставляется» имеет значение «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

Вы добавили ключ 'Privacy - Contacts Usage Description' в свой info.plist? Он поддерживается в iOS 6.0 и более поздних версиях. –

+0

Я попробовал iOS ios 8 и 9 все еще не работает –

ответ

0

Если вы хотите получить доступ к информации о существующих контактах в адресной книге следующим код может помочь вам :)

Шаг 1: Добавить

#import <AddressBook/AddressBook.h> 

Шаг 2: вызов следующий метод из viewDidLoad

-(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. 
} 

Шаг 3: Добавить этот метод в код Этот метод дает вам всю необходимую информацию для конкретного контакта.

- (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

Нет, у меня есть не получил контакт с вашим кодом. Мое приложение не имеет к ним доступа. Настройки конфиденциальности, нет доступа для доступа ... –

Смежные вопросы