我在地址簿iphone 4s取消联系无法正常工作

时间:2013-01-31 11:03:21

标签: iphone addressbook

+(NSMutableArray *)getLastName
{

   ABAddressBookRef addressBook = ABAddressBookCreate();
    NSMutableArray *lastNameArray = [[NSMutableArray alloc]init];
    ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
    CFIndex numberOfContacts  = ABAddressBookGetPersonCount(addressBook);
    NSLog(@"%ld",numberOfContacts);
    CFArrayRef people = (__bridge CFArrayRef)((__bridge NSArray*)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByLastName));
    NSArray * tempArray = [[NSArray alloc]init];
    tempArray = (__bridge  NSArray *)(people);
    if ([tempArray count]>0) {
    for (int personIndex = 0; personIndex < [tempArray count]-1; personIndex++) {
        ABRecordRef person = (__bridge ABRecordRef)([tempArray objectAtIndex:personIndex]);
        ABMultiValueRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
        NSString *lastNameString = (__bridge NSString *)lastName;
        if (lastName!=nil)
            [lastNameArray addObject:lastNameString];
          }
    }
    return lastNameArray;
}

我正在使用xcode 6.0。 iphone 3s工作正常,但iphone 4s和iphone 5无法使用该代码

3 个答案:

答案 0 :(得分:2)

-(void)_addContactToAddressBook
{
char *lastNameString, *firstNameString,*emailString;
NSMutableArray *arrname =[[NSMutableArray alloc] init];
NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
// AddressBook

ABAddressBookRef ab = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(ab);
CFIndex nPeople = ABAddressBookGetPersonCount(ab);

for(int i = 0; i < nPeople; i++)
{   
    [dict removeAllObjects];
    ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);

    CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
    CFStringRef lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
    ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonEmailProperty);
    CFStringRef email;
    if (ABMultiValueGetCount(multi) > 0) {
        // collect all emails in array
        for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++) 
        {
            CFStringRef emailRef = ABMultiValueCopyValueAtIndex(multi, i);
            //[personDealingWithEmails addObject:(NSString *)emailRef];
            email=emailRef;
            CFRelease(emailRef);
        }
    }
    else
    {
        email=nil;
    }

    CFDataRef imgData;
    if(ABPersonHasImageData(ref))
    {
        imgData = ABPersonCopyImageData(ref);
    }else {
        imgData=nil;
    }

    static char* fallback = "";
    int fbLength = strlen(fallback);

    int firstNameLength = fbLength;
    bool firstNameFallback = true;

    int lastNameLength = fbLength;
    bool lastNameFallback = true;

    int emailLength = fbLength;
    bool emailFallback = true;

    if (firstName != NULL)
    {
        firstNameLength = (int) CFStringGetLength(firstName);
        firstNameFallback = false;
    }
    if (lastName != NULL)
    {
        lastNameLength = (int) CFStringGetLength(lastName);
        lastNameFallback = false;
    }
    if (email !=  NULL)
    {
        emailLength = (int) CFStringGetLength(email);
        emailFallback = false;
    }


    if (firstNameLength == 0)
    {
        firstNameLength = fbLength;
        firstNameFallback = true;
    }
    if (lastNameLength == 0)
    {
        lastNameLength = fbLength;
        lastNameFallback = true;
    }
    if (emailLength == 0)
    {
        emailLength = fbLength;
        emailFallback = true;
    }


    firstNameString = malloc(sizeof(char)*(firstNameLength+1));
    lastNameString = malloc(sizeof(char)*(lastNameLength+1));
    emailString = malloc(sizeof(char)*(emailLength+1));

    if (firstNameFallback == true)
    {
        strcpy(firstNameString, fallback);
    }
    else
    {
        CFStringGetCString(firstName, firstNameString, 10*CFStringGetLength(firstName), kCFStringEncodingASCII);
    }

    if (lastNameFallback == true)
    {
        strcpy(lastNameString, fallback);
    }
    else
    {
        CFStringGetCString(lastName, lastNameString, 10*CFStringGetLength(lastName), kCFStringEncodingASCII);
    }

    if (emailFallback == true)
    {
        strcpy(emailString, fallback);
    }
    else
    {
        CFStringGetCString(email, emailString, 10*CFStringGetLength(email), kCFStringEncodingASCII);
    }

    printf("%d.\t%s %s\n", i, firstNameString, lastNameString);
    NSString *fname= [NSString stringWithFormat:@"%s",firstNameString];
    NSString *lname= [NSString stringWithFormat:@"%s",lastNameString];
    NSString *fullName=[NSString stringWithFormat:@"%@%@%@",fname,([fname length]!=0)?@" ":@"",lname];
    NSString *eMail= [NSString stringWithFormat:@"%s",emailString];
    NSData *myData;
    if (imgData) {
        myData=(__bridge NSData *)imgData;
    }else {
        myData=nil;
    }


    //fetch Phone num
    ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(ref, kABPersonPhoneProperty);
    NSArray* phoneNumbers = (__bridge NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
    CFRelease(phoneNumberProperty);

    // Do whatever you want with the phone numbers
    //NSLog(@"Phone numbers = %@", phoneNumbers);
    NSString *PhoneNum = [phoneNumbers objectAtIndex:0];


    //--------------remove special char form string(Phone number)-----------------      
    NSString *originalString = PhoneNum;

    //NSLog(@"%@", originalString);
    NSMutableString *strippedString = [NSMutableString 
                                       stringWithCapacity:originalString.length];

    NSScanner *scanner = [NSScanner scannerWithString:originalString];
    NSCharacterSet *numbers = [NSCharacterSet 
                               characterSetWithCharactersInString:@"0123456789"];

    while ([scanner isAtEnd] == NO) {
        NSString *buffer;
        if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
            [strippedString appendString:buffer];

        } else {
            [scanner setScanLocation:([scanner scanLocation] + 1)];
        }
    }

    if([fname isEqualToString:@""] && [lname isEqualToString:@""]){

    }else{

        if (myData) {
            UIImage *img = [UIImage imageWithData:myData];

            [dict setObject:img forKey:@"imgData"];         
        }

        [dict setValue:fname forKey:@"fname"];
        [dict setValue:lname forKey:@"lname"];
        [dict setValue:fullName forKey:@"fullName"];
        [dict setValue:eMail forKey:@"email"];
        [dict setValue:strippedString forKey:@"phoneNumber"];
        [dict setValue:@"addressbook" forKey:@"type"];
        [arrname addObject:[dict copy]];
    }

    if (firstName != NULL)
    {
        CFRelease(firstName);
    }
    if (imgData != NULL)
    {
        CFRelease(imgData);
    }
    if (lastName != NULL)
    {
        CFRelease(lastName);
    }
    if (email != NULL)
    {
        CFRelease(email);
    }
    free(firstNameString);
    free(lastNameString);
    free(emailString);
}


for (int i=0; i<[arrname count]; i++) 
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:@"0" forKey:@"sel"];
    [arrTemp addObject:dict];
}

[arrallcontacts addObjectsFromArray:arrname];

[arraddedcontactsfulllist addObjectsFromArray:arrallcontacts];
NSSortDescriptor *sortByfullName = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:sortByfullName];
NSArray *sorted = [arraddedcontactsfulllist sortedArrayUsingDescriptors:descriptors];
[arraddedcontactsfulllist removeAllObjects];
[arraddedcontactsfulllist addObjectsFromArray:sorted];
[arraddedcontacts removeAllObjects];
[arraddedcontacts addObjectsFromArray:sorted];

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
tblview.alpha=1;
[UIView commitAnimations];
[tblview reloadData];

if (![[[[NSUserDefaults standardUserDefaults] objectForKey:@"USER_DETAIL"] objectForKey:@"facebook"] isEqualToString:@"Unauthenticate"]) {

    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    [self performSelector:@selector(getfacebookfriends) withObject:nil afterDelay:0.0001];
}
}
-(void)fetchIphoneContact
{
if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0)
{
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            // First time access has been granted, add the contact
            [self _addContactToAddressBook];
            [tblview reloadData];
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
        // The user has previously given access, add the contact
        [self _addContactToAddressBook];
        [tblview reloadData];
    }
    else {
        // The user has previously denied access
        // Send an alert telling user to change privacy setting in settings app
        DisplayAlertWithTitle(APP_Name, @"You can change your privacy setting in settings app");
    }

}
else
{
    [self _addContactToAddressBook];
}
}

这适用于iOS6及更低版本..

答案 1 :(得分:1)

我认为问题在于你的iOS版本......如果你使用的是iOS 6.0,那么ABAddressBookCreate()将无效......对于iOS 5.1或以前的版本都没问题......所以你可以这样做,

ABAddressBookRef addressBook;

if ([self isABAddressBookCreateWithOptionsAvailable])
{
    // iOS 6
    CFErrorRef error = nil;
    addressBook = ABAddressBookCreateWithOptions(NULL,&error);

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
                                             {
                                             });
    ABAddressBookRevert(addressBook);
}
else
{
    // iOS 4/5
    addressBook = ABAddressBookCreate();
}



-(BOOL)isABAddressBookCreateWithOptionsAvailable
{
    return &ABAddressBookCreateWithOptions != NULL;
}

通过此,您可以获得所有联系人...... :)

答案 2 :(得分:1)

在IOS中可能有不同的方法来检索AddressBook,但我用来检索地址簿的一种方法如下,确保使用ABPeoplePickerNavigationControllerDelegate你可以点击这样的按钮打开AddressBook Controller

-(IBAction)getContact:(id)sender {
    // creating the picker
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    // place the delegate of the picker to the controll
    picker.peoplePickerDelegate = self;

    [self presentModalViewController:picker animated:YES];
}

显示addressBook后,您可以使用委托方法接收联系信息,如下所示

- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {

// setting the first name
firstNameTxt.text = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);

// setting the last name
lastNameTxt.text = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);

// setting the number
/*
 this function will set the first number it finds

 if you do not set a number for a contact it will probably
 crash
 */
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
telefonTxt.text = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, 0);

ABMultiValueRef multi1 = ABRecordCopyValue(person, kABPersonEmailProperty);
emailTxt.text = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi1, 0);


// remove the controller
[self dismissModalViewControllerAnimated:YES];

return NO;

}