Onelong

分享知识,与你一起进步......
RSS icon Home icon
  • ios 通讯录代码

    post by onelong / 2014-1-13 16:10 Monday [apple]

    需要注意的就是iOS6中新的用户隐私保护使得调用 ABAddressBookCreate() 时会弹出alert让用户确认是否允许,需要加上代码:

      // 如果为iOS6以上系统,需要等待用户确认是否允许访问通讯录。    

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)    

    {        

    addressBook = ABAddressBookCreateWithOptions(NULL, NULL);        

    //等待同意后向下执行        

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);       

     ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)                                                 {                                                     dispatch_semaphore_signal(sema);                                                 });        

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);         

    dispatch_release(sema);     

    不然addressBook在用户确认操作前是NULL,调用会导致程序crash。

     

     

     -(IBAction)onClickbutton:(id)sender

        {

            NSMutableArray* personArray =[[[NSMutableArray alloc] init] autorelease];

            ABAddressBookRef addressBook =ABAddressBookCreate();

            NSString*firstName,*lastName,*fullName;

            personArray =(NSMutableArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);

            if([sender tag]==0){

     

                for(id person in personArray)

                {

                    firstName =(NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);

                    firstName =[firstName stringByAppendingFormat:@" "];

                    lastName =(NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);   

                    fullName =[firstName stringByAppendingFormat:@"%@",lastName];

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

                    ABMultiValueRef phones =(ABMultiValueRef)ABRecordCopyValue(person, kABPersonPhoneProperty);

                    for(int i =0;i <ABMultiValueGetCount(phones); i++)

                    { 

                        NSString*phone =(NSString*)ABMultiValueCopyValueAtIndex(phones, i);

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

                    }

                    ABMultiValueRef mails =(ABMultiValueRef)ABRecordCopyValue(person, kABPersonEmailProperty);

                    for(int i =0;i <ABMultiValueGetCount(mails); i++)

                    { 

                        NSString*mail =(NSString*)ABMultiValueCopyValueAtIndex(mails, i);

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

                    }       

                }   

            }else{

                //删除信息

                //返回所有联系人到一个数组中

                CFArrayRef personArray =ABAddressBookCopyArrayOfAllPeople(addressBook);

                CFIndex personCount =ABAddressBookGetPersonCount(addressBook);

                  for(int i =0;i<personCount;i++){

                      ABRecordRefref=CFArrayGetValueAtIndex(personArray, i);

                      CFStringRef firstName1 =ABRecordCopyValue(ref, kABPersonFirstNameProperty);

                      CFStringRef lastName1 =ABRecordCopyValue(ref, kABPersonLastNameProperty);

                      NSString*contactFirstLast =[NSString stringWithFormat: @"%@%@",(NSString*)firstName1,(NSString*)lastName1];

                    if([contactFirstLast isEqualToString:@"徐梦"]){

                        //删除联系人

                        ABAddressBookRemoveRecord(addressBook,ref,nil);

                    }

                }

                //保存电话本

                ABAddressBookSave(addressBook,nil);  

                //释放内存

                //CFRelease(personRef);

        //        CFRelease(addressbookRef); 

            }

        }

     

    添加联系人

     //name

        ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();

        ABRecordRef newPerson = ABPersonCreate();

        CFErrorRef error = NULL;

        ABRecordSetValue(newPerson, kABPersonFirstNameProperty, firsrName.text, &error);

        ABRecordSetValue(newPerson, kABPersonLastNameProperty, lastName.text, &error);

        ABRecordSetValue(newPerson, kABPersonOrganizationProperty, company.text, &error);

        ABRecordSetValue(newPerson, kABPersonFirstNamePhoneticProperty, firsrNamePY.text, &error);

        ABRecordSetValue(newPerson, kABPersonLastNamePhoneticProperty, lastNamePY.text, &error);

        //phone number

        ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);

        ABMultiValueAddValueAndLabel(multiPhone, houseNumber.text, kABPersonPhoneHomeFAXLabel, NULL);

        ABMultiValueAddValueAndLabel(multiPhone, mobileNumber.text, kABPersonPhoneMobileLabel, NULL);

        ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone, &error);

        CFRelease(multiPhone);

        //email

        ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);

        ABMultiValueAddValueAndLabel(multiEmail, email.text, kABWorkLabel, NULL);

        ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);

        CFRelease(multiEmail);

        //picture

        NSData *dataRef = UIImagePNGRepresentation(head.image);

        ABPersonSetImageData(newPerson, (CFDataRef)dataRef, &error);

        ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);

        ABAddressBookSave(iPhoneAddressBook, &error);

        CFRelease(newPerson);

        CFRelease(iPhoneAddressBook);

     

     

    ABAddressBookRef addressBook = ABAddressBookCreate();

     

        CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);

        

        for(int i = 0; i < CFArrayGetCount(results); i++)

        {

            ABRecordRef person = CFArrayGetValueAtIndex(results, i);

            //读取firstname

            NSString *personName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);

            if(personName != nil)

                textView.text = [textView.text stringByAppendingFormat:@"\n姓名:%@\n",personName];

            //读取lastname

            NSString *lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);

            if(lastname != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastname];

            //读取middlename

            NSString *middlename = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);

            if(middlename != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlename];

            //读取prefix前缀

            NSString *prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);

            if(prefix != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",prefix];

            //读取suffix后缀

            NSString *suffix = (NSString*)ABRecordCopyValue(person, kABPers*****uffixProperty);

            if(suffix != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",suffix];

            //读取nickname呢称

            NSString *nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);

            if(nickname != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",nickname];

            //读取firstname拼音音标

            NSString *firstnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);

            if(firstnamePhonetic != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",firstnamePhonetic];

            //读取lastname拼音音标

            NSString *lastnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);

            if(lastnamePhonetic != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastnamePhonetic];

            //读取middlename拼音音标

            NSString *middlenamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);

            if(middlenamePhonetic != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlenamePhonetic];

            //读取organization公司

            NSString *organization = (NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);

            if(organization != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",organization];

            //读取jobtitle工作

            NSString *jobtitle = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);

            if(jobtitle != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",jobtitle];

            //读取department部门

            NSString *department = (NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);

            if(department != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",department];

            //读取birthday生日

            NSDate *birthday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);

            if(birthday != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",birthday];

            //读取note备忘录

            NSString *note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);

            if(note != nil)

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",note];

            //第一次添加该条记录的时间

            NSString *firstknow = (NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);

            NSLog(@"第一次添加该条记录的时间%@\n",firstknow);

            //最后一次修改該条记录的时间

            NSString *lastknow = (NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);

            NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

            

            //获取email多值

            ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);

            int emailcount = ABMultiValueGetCount(email);    

            for (int x = 0; x < emailcount; x++)

            {

                //获取email Label

                NSString* emailLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));

                //获取email值

                NSString* emailContent = (NSString*)ABMultiValueCopyValueAtIndex(email, x);

                textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent];

            }

            //读取地址多值

            ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);

            int count = ABMultiValueGetCount(address);    

            

            for(int j = 0; j < count; j++)

            {

                //获取地址Label

                NSString* addressLabel = (NSString*)ABMultiValueCopyLabelAtIndex(address, j);

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",addressLabel];

                //获取該label下的地址6属性

                NSDictionary* personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);        

                NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];

                if(country != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"国家:%@\n",country];

                NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];

                if(city != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"城市:%@\n",city];

                NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];

                if(state != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"省:%@\n",state];

                NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];

                if(street != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"街道:%@\n",street];

                NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];

                if(zip != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"邮编:%@\n",zip];    

                NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];

                if(coutntrycode != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"国家编号:%@\n",coutntrycode];    

            }

            

            //获取dates多值

            ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);

            int datescount = ABMultiValueGetCount(dates);    

            for (int y = 0; y < datescount; y++)

            {

                //获取dates Label

                NSString* datesLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));

                //获取dates值

                NSString* datesContent = (NSString*)ABMultiValueCopyValueAtIndex(dates, y);

                textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent];

            }

            //获取kind值

            CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);

            if (recordType == kABPersonKindOrganization) {

                // it's a company

                NSLog(@"it's a company\n");

            } else {

                // it's a person, resource, or room

                NSLog(@"it's a person, resource, or room\n");

            }

            

            

            //获取IM多值

            ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);

            for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)

            {

                //获取IM Label

                NSString* instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);

                textView.text = [textView.text stringByAppendingFormat:@"%@\n",instantMessageLabel];

                //获取該label下的2属性

                NSDictionary* instantMessageContent =(NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);        

                NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];

                if(username != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"username:%@\n",username];

                

                NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];

                if(service != nil)

                    textView.text = [textView.text stringByAppendingFormat:@"service:%@\n",service];            

            }

            

            //读取电话多值

            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);

            for (int k = 0; k<ABMultiValueGetCount(phone); k++)

            {

                //获取电话Label

                NSString * personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));

                //获取該Label下的电话值

                NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);

                    

                textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone];

            }

            

            //获取URL多值

            ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);

            for (int m = 0; m < ABMultiValueGetCount(url); m++)

            {

                //获取电话Label

                NSString * urlLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));

                //获取該Label下的电话值

                NSString * urlContent = (NSString*)ABMultiValueCopyValueAtIndex(url,m);

                

                textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent];

            }

            

            //读取照片

            NSData *image = (NSData*)ABPersonCopyImageData(person);

                

     

            UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];

            [myImage setImage:[UIImage imageWithData:image]];

            myImage.opaque = YES;

            [textView addSubview:myImage];

            

     

        

        }

        

        CFRelease(results);

        CFRelease(addressBook);

     

     

    //定义通讯录名字为addressbook 

    ABAddressBookRef addressBook = ABAddressBookCreate(); 

    //将通讯录中的信息用数组方式读出 

    CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook); 

    //获取通讯录中联系人 

    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook); 

        

        iphoneContactList = [[NSMutableArray alloc] initWithCapacity:0]; 

        for (int i = 0; i < nPeople; i++) 

        { 

            

            IphoneContact * iphoneContact = [[IphoneContact alloc] init]; 

            

            NSData *imageData = [[[NSData alloc] init]autorelease]; 

            NSString *address = [[[NSString alloc] init]autorelease]; 

            

            

            ABRecordRef person = CFArrayGetValueAtIndex(contacts, i);//取出某一个人的信息 

           NSInteger lookupforkey =(NSInteger)ABRecordGetRecordID(person);//读取通讯录中联系人的唯一标识 

           NSDate * createDate = (NSDate *)ABRecordCopyValue(person, kABPersonCreationDateProperty);// 读取通讯录中联系人的创建日期 

            NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; 

            [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 

            NSString* birthDay = [formatter stringFromDate:createDate]; 

            [formatter release]; 

          

            

            

            NSString *createDate1 = [birthDay stringByReplacingOccurrencesOfString:@"-" withString:@""]; 

            NSString *createDate2 = [createDate1 stringByReplacingOccurrencesOfString:@":" withString:@""]; 

            NSString *createDate3 = [createDate2 stringByReplacingOccurrencesOfString:@" " withString:@""]; 

            NSLog(@"1111========%@",createDate3); 

            NSLog(@"222222========%@",birthDay); 

            NSString *indexInIphone = [NSString stringWithFormat:@"%i",lookupforkey]; 

            iphoneContact.lookUpKey = [createDate3 stringByAppendingString:indexInIphone]; 

           //上诉操作是将某个联系人的标识号与创建日期进行组合,得到唯一的标识,是为了当时特殊的需要,一般不会有这种变态应用,这是因为ABRecordGetRecordID在一个手机中是唯一的,即使删掉某一个联系人,这个号也不会在被占用。 

            

            

            

                  //读取联系人姓名属性 

            if (ABRecordCopyValue(person, kABPersonLastNameProperty)&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))== nil) { 

                iphoneContact.contactName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty); 

            }else if (ABRecordCopyValue(person, kABPersonLastNameProperty) == nil&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))){ 

                iphoneContact.contactName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); 

            }else if (ABRecordCopyValue(person, kABPersonLastNameProperty)&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))){ 

                

                NSString *first =(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); 

                NSString *last = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty); 

                iphoneContact.contactName = [NSString stringWithFormat:@"%@%@",last,first]; 

            }                     

             //读取联系人姓名的第一个汉语拼音,用于排序,调用此方法需要在程序中加载pingyin.h pingyin.c,如有需要请给我联系。     

            iphoneContact.pinyin =[[NSString stringWithFormat:@"%c",pinyinFirstLetter([iphoneContact.contactName characterAtIndex:0])] uppercaseString]; 

            

            

            //读取联系人公司信息                    

            

            iphoneContact.contactCompany = (NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty); 

            

            //读取联系人工作 

            iphoneContact.contactJob = (NSString *)ABRecordCopyValue(person, kABPersonJobTitleProperty); 

            

            

            

            

            //读取联系人email信息,email有好几种,比如工作邮箱,家庭邮箱,通过ABMultiValueCopyLabelAtIndex 属性来判断,下面给出了例子                

            ABMultiValueRef emailForWORK = ABRecordCopyValue(person, kABPersonEmailProperty); 

            if ((emailForWORK != nil)&&ABMultiValueGetCount(emailForWORK)>0) { 

                

                for (int k = 0; k < ABMultiValueGetCount(emailForWORK); k++) { 

                    NSString * aEmail = (NSString *)ABMultiValueCopyValueAtIndex(emailForWORK, k); 

                    NSString * aEmailLabel = (NSString *)ABMultiValueCopyLabelAtIndex(emailForWORK, k); 

                    

                    if ([aEmailLabel isEqualToString:@"_$!<Work>!$_"]) { 

                        iphoneContact.contactEmail = aEmail; 

                    }       

                } 

            } 

            

            

            //读取通信地址信息,在ios中国家,省份,城市,区,街道,号都是单独存储的,需要单独读取然后在组合(根据需要) 

            ABMultiValueRef addressTotal = ABRecordCopyValue(person, kABPersonAddressProperty); 

            if (addressTotal) { 

                

                int count = ABMultiValueGetCount(addressTotal);    

                

                for(int j = 0; j < count; j++) 

                { 

                    

                    NSDictionary* personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(addressTotal, j);        

                    NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey]; 

                    if(country != nil) 

                        address = [NSString stringWithFormat:@"%@",country]; 

                    NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey]; 

                    if(city != nil) 

                        address = [address stringByAppendingFormat:@"%@",city]; 

                    NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey]; 

                    if(state != nil) 

                        address = [address stringByAppendingFormat:@"%@",state]; 

                    NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey]; 

                    if(street != nil) 

                        address = [address stringByAppendingFormat:@"%@",street]; 

                     

                }  

                

                iphoneContact.contactAdress = address; 

            } 

            

            

            

            

            //读取电话信息,和emial类似,也分为工作电话,家庭电话,工作传真,家庭传真。。。。 

            

            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty); 

            

            if ((phone != nil)&&ABMultiValueGetCount(phone)>0) { 

                

                for (int m = 0; m < ABMultiValueGetCount(phone); m++) { 

                    NSString * aPhone = [(NSString *)ABMultiValueCopyValueAtIndex(phone, m) autorelease]; 

                    NSString * aLabel = [(NSString *)ABMultiValueCopyLabelAtIndex(phone, m) autorelease]; 

                    

                    if ([aLabel isEqualToString:@"_$!<Mobile>!$_"]) { 

                        iphoneContact.contactMobile= aPhone; 

                        

                    } 

                    

                    if ([aLabel isEqualToString:@"_$!<WorkFAX>!$_"]) { 

                        iphoneContact.contactFax = aPhone; 

                    } 

                    

                    if ([aLabel isEqualToString:@"_$!<Work>!$_"]) { 

                        iphoneContact.contactTelephone= aPhone; 

                    }       

                } 

            } 

            

            

            

            

            //读取照片信息 

            imageData = (NSData *)ABPersonCopyImageData(person); 

            UIImage *myImage = [UIImage imageWithData:imageData]; 

            CGSize newSize = CGSizeMake(55, 55); 

            UIGraphicsBeginImageContext(newSize); 

            [myImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; 

            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 

            UIGraphicsEndImageContext();//上诉代码实现图片压缩,可根据需要选择,现在是压缩到55*55 

            

            imageData = UIImagePNGRepresentation(newImage); 

            

            if (imageData) { 

                NSData * BimageData = [GTMBase64 encodeData:imageData]; 

                iphoneContact.headImage= [[NSString alloc] initWithData:BimageData encoding:NSUTF8StringEncoding]; 

            } 

                   

            iphoneContact.isSelected = NO; 

            [iphoneContactList addObject:iphoneContact];  //将读取的某一个人信息放到我们自定义的可变数组中        

            

        }

    标签: ios
    引用地址:
     

    我要评论