iOS8中的地址簿授权

前端之家收集整理的这篇文章主要介绍了iOS8中的地址簿授权前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
自从我在iOS 8上更新以来,我有权获得访问AddressBook的权限.

在iOS 7中,系统询问用户是否允许我的应用程序访问他的地址簿,但是因为iOS8没有任何请求.每次我在启动“MyGetAddressesOfContacts”函数之前检查ABAddressBookGetAuthorizationStatus时,Status等于kABAuthorizationStatusNotDetermined.
就像你在这里看到的:

if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied)
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No permission" message:@"This App has no permition to access your contacts. Please check it in your privacy settings of your device." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];

    return nil;
}

// This AlertView pops up every time!
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Why this App needs your contacts" message:@"In the following your device will ask you whether this App is allowed to access your contacts. [...]" delegate:self cancelButtonTitle:@"I understand" otherButtonTitles: nil];

    [alert show];
}

在此检查之后,我将启动MyGetAddressesOfContacts函数,如下所示:

ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *contactArr = (NSArray *)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSMutableDictionary *dPersons = [[NSMutableDictionary alloc] init];

for (int i = 0; i < [contactArr count]; i++)
{
    ABRecordRef person = (ABRecordRef)CFBridgingRetain([contactArr objectAtIndex:i]);
    NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);
    NSString *lastName = (__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);
    NSString *sPersonName = [NSString stringWithFormat:@"%@ %@",firstName,lastName];

    ABMultiValueRef address = ABRecordCopyValue(person,kABPersonAddressProperty);
    NSString *sAddress;

    for(CFIndex j = 0; j < ABMultiValueGetCount(address); j++)
    {
        CFDictionaryRef addressDict = ABMultiValueCopyValueAtIndex(address,j);

        CFStringRef streetValue = CFDictionaryGetValue(addressDict,kABPersonAddressStreetKey);
        CFStringRef cityValue = CFDictionaryGetValue(addressDict,kABPersonAddressCityKey);
        CFStringRef countryValue = CFDictionaryGetValue(addressDict,kABPersonAddressCountryKey);

        sAddress = [NSString stringWithFormat:@"%@ %@,%@",streetValue,cityValue,countryValue];
        [dPersons setObject:sAddress forKey: [NSString stringWithFormat:@"%@%d %ld",@"AddressFromNameID",i,j]];
    }

    [dPersons setObject:sPersonName forKey: [NSString stringWithFormat:@"%@ %d",@"NameWithID",i]];
}

return dPersons;

希望有人能提供帮助.

解决方法

创建AB后……
ABAddressBookRef addressBook = ABAddressBookCreate();

打电话给以下……

ABAddressBookRequestAccessWithCompletion(addressBook,nil);

这将显示用户允许您的应用程序访问“联系人”的提示;作为第二个参数,您可以获得结果回调并相应地执行操作.请参考Apple documentation

猜你在找的iOS相关文章