iOS Address Book integration, compatible with iOS789 notation, with demo

Source: Internet
Author: User

Apple's Address book feature is different in Ios7,ios8,ios9, iOS7 and 8 use <AddressBookUI/AddressBookUI.h>, but the two system versions of the proxy method have some changes,  Some proxy methods have labeled ns_deprecated_ios(2_0, 8_0) and recommend another proxy method to correspond to it. and iOS8 to iOS9 is directly discarded <AddressBookUI/AddressBookUI.h> replaced by <contactsui/ Contactsui.h>, the latter being the OC call, was said to have sparked cheers when Apple announced the abandonment of Addressbookui. This is also the use of the Address Book function to consider the version of the various judgments, I was in the work encountered this pit, and then a compatible package. Hope to solve this problem.

I think the class structure of the address book doesn't have to be listed in detail like Sdwebimage or core location. We use the Address book without the three features:

1. Click on the pop-up contacts page, select a contact's phone and fill in the information directly into the page input box.

2. Traverse all the contacts data to do batch operation, build a new page or upload directly.

3. Write a message to the Address Book.

Here's a comparison of the iOS789, and finally the demo (a packaged library that provides a very handy API). Friends who do not care about internal implementations can pull directly to the demo section.

first, the permission to get the address book

IOS7 and 8 remain consistent

    Abauthorizationstatus status = Abaddressbookgetauthorizationstatus ();    Abaddressbookref addressbookref = abaddressbookcreatewithoptions (null, NULL);    if (status = = kabauthorizationstatusnotdetermined) {        NSLog (@ "not yet asked");        Abaddressbookrequestaccesswithcompletion (Addressbookref, ^ (bool granted, cferrorref error) {            if (granted) {                NSLog (@ "Click to agree");            } else{                NSLog (@ "Click to reject");}        );    else if (status = = kabauthorizationstatusauthorized) {        NSLog (@ "authorized");        [Self Loadperson];    } else {        NSLog (@ "no authorization");        Popup window prompt to get permission    }

IOS9 and later call method changed to

     Cnauthorizationstatus status = [Cncontactstore authorizationstatusforentitytype:cnentitytypecontacts];    if (status = = cnauthorizationstatusnotdetermined) {[[[        Cncontactstore Alloc]init] Requestaccessforentitytype: Cnentitytypecontacts completionhandler:^ (BOOL Granted, Nserror * _nullable error) {            NSLog (@ "not yet asked");            if (granted) {                NSLog (@ "click Agree");                [Self Loadperson];            } else{                NSLog (@ "click Reject");}        ];}    else if (status = = cnauthorizationstatusauthorized) {         NSLog (@ already authorized);    } else {        NSLog (@ "not authorized");    }    
second, pop-up contacts selection interface

The iOS7 is written as follows, and the return value of the proxy method is mostly of type bool.

-(BOOL) Peoplepickernavigationcontroller: (Abpeoplepickernavigationcontroller *) peoplepicker Shouldcontinueafterselectingperson: (abrecordref) person{return YES;} -(BOOL) Peoplepickernavigationcontroller: (Abpeoplepickernavigationcontroller *) peoplepicker Shouldcontinueafterselectingperson: (abrecordref): (Abpropertyid) Property identifier: (    Abmultivalueidentifier) identifier{Abmultivalueref phone = abrecordcopyvalue (person, kabpersonphoneproperty);    Long index = Abmultivaluegetindexforidentifier (phone,identifier);        NSString *phoneno = (__bridge NSString *) abmultivaluecopyvalueatindex (phone, index);    Cfstringref lastName = Abrecordcopyvalue (person, kabpersonlastnameproperty);        Cfstringref firstName = Abrecordcopyvalue (person, kabpersonfirstnameproperty);    NSString *lastname = (__bridge_transfer NSString *) (LastName);        NSString *firstname = (__bridge_transfer NSString *) (FirstName); if (phone) {[Peoplepicker dismissviewcontrolleranimated:yES Completion:nil];    return NO; } return YES;

IOS8 Agent method changed, changed to the following two, but the method inside the value is basically the same

Click on the Address Book name will exit-(void) Peoplepickernavigationcontroller: (Abpeoplepickernavigationcontroller *) peoplepicker Didselectperson: (abrecordref) person;//Click on the name inside the phone or the mailbox will exit-(void) Peoplepickernavigationcontroller: ( Abpeoplepickernavigationcontroller *) Peoplepicker Didselectperson: (abrecordref) Person property: (Abpropertyid) Property identifier: (Abmultivalueidentifier) identifier;

As to which method will be called, according to the actual need to choose, in the method of the popup interface Predicateforselectionofperson This property false is called the following.

    Abpeoplepickernavigationcontroller *PICKERVC = [[Abpeoplepickernavigationcontroller alloc] init];    Pickervc.predicateforselectionofperson = [Nspredicate predicatewithvalue:false];    Pickervc.peoplepickerdelegate = self;    [Target PRESENTVIEWCONTROLLER:PICKERVC Animated:yes Completion:nil];

The pop-up selector method and proxy method under the IOS9 system are as follows

 Pop-up selector-(void) presentpageontarget{cncontactpickerviewcontroller *CONTACTVC = [[Cncontactpickerviewcontroller     ALLOC] init];     Contactvc.delegate = self; [Target PRESENTVIEWCONTROLLER:CONTACTVC Animated:yes completion:nil];}    Proxy Method-(void) Contactpicker: (Cncontactpickerviewcontroller *) Picker didselectcontact: (cncontact *) contact{    Sxpersoninfoentity *personentity = [sxpersoninfoentity new];    NSString *lastname = contact.familyname;    NSString *firstname = contact.givenname;    NSLog (@ "%@%@", LastName, FirstName);    Personentity.lastname = LastName;        Personentity.firstname = FirstName;    nsmutablestring *fullname = [[NSString stringwithformat:@ "%@%@", Lastname,firstname] mutablecopy]; [FullName replaceoccurrencesofstring:@ "(null)" withstring:@ "" Options:nscaseinsensitivesearch range:nsmakerange (0,    Fullname.length)];        Personentity.fullname = fullname;    NSString *fullphonestr = [NSString string];    Nsarray *phonenums = contact.phonenumbers; FoR (Cnlabeledvalue *labeledvalue in phonenums) {nsstring *phonelabel = Labeledvalue.label;        Cnphonenumber *phonenumer = Labeledvalue.value;        NSString *phonevalue = Phonenumer.stringvalue;        NSLog (@ "%@%@", Phonelabel, Phonevalue);            if (Phonevalue.length > 0) {fullphonestr = [fullphonestr stringbyappendingstring:phonevalue];        FULLPHONESTR = [Fullphonestr stringbyappendingstring:@ ","]; }} if (Fullphonestr.length > 1) {personentity.phonenumber = [fullphonestr substringtoindex:fullphonestr.    LENGTH-1]; } self.chooseaction (personentity);}

This is a click on the name of the direct callback method, if you want to click on the property and then callback, you need to add this line

Contactvc.predicateforselectionofcontact = [Nspredicate predicatewithvalue:false];//proxy method call-(void) ContactPicker: ( Cncontactpickerviewcontroller *) Picker Didselectcontactproperty: (Cncontactproperty *) ContactProperty

third, get all the address book information

The way to get all the contacts in bulk is a bit lengthy, it is not affixed here, only paste the iOS9, iOS7 and 8 of the code in the demo.

-(void) printallperson{//Get Cncontactstore *contactstore = [[CNCon    Tactstore alloc] init];    Nsarray *keys = @[cncontactgivennamekey, Cncontactfamilynamekey, Cncontactphonenumberskey];        Cncontactfetchrequest *request = [[Cncontactfetchrequest alloc] initwithkeystofetch:keys];  Traverse [Contactstore enumeratecontactswithfetchrequest:request error:nil usingblock:^ (cncontact * _Nonnull Contact, BOOL        * _nonnull stop) {nsstring *lastname = contact.familyname;        NSString *firstname = contact.givenname;        NSLog (@ "%@%@", LastName, FirstName);        Nsarray *phonenums = contact.phonenumbers;            For (Cnlabeledvalue *labeledvalue in phonenums) {nsstring *phonelabel = Labeledvalue.label;            Cnphonenumber *phonenumer = Labeledvalue.value;            NSString *phonevalue = Phonenumer.stringvalue;        NSLog (@ "%@%@", Phonelabel, Phonevalue); }    }];}

Iv. Writing Contacts

Because this function is a bit of a heavyweight, write to write, name, phone, email, address, etc., this will make the API too complex. For the time being, most of the practice I've seen is if the user has given the Address Book permission to insert a name + phone, I have made only these two parameters of the API, of course, when used can also be fully expanded into more parameter.

IOS7 and 8

-(void) creatitemwithname :(NSString *) name Phone: (NSString *) phone{if ((Name.length < 1) | | (Phone.length < 1))        {NSLog (@ "Input attribute cannot be empty");    Return        } cferrorref error = NULL;    Abaddressbookref addressbook = abaddressbookcreatewithoptions (NULL, &error);    Abrecordref NewRecord = Abpersoncreate ();        Abrecordsetvalue (NewRecord, Kabpersonfirstnameproperty, (__bridge cftyperef) name, &error);    Abmutablemultivalueref multi = abmultivaluecreatemutable (Kabmultistringpropertytype);        Abmultivalueaddvalueandlabel (Multi, (__bridge cftyperef) name, Kabpersonphonemobilelabel, NULL);    Abrecordsetvalue (NewRecord, Kabpersonphoneproperty, Multi, &error);        Cfrelease (multi);        Abaddressbookaddrecord (AddressBook, NewRecord, &error);    Abaddressbooksave (AddressBook, &error);    Cfrelease (NewRecord); Cfrelease (AddressBook);}  

IOS9 under

-(void) Creatitemwithname: (NSString *) name Phone: (NSString *) phone{    //Create object//    This inside can add multiple phone, email, address and so on. The feeling usage is not high, only provides the most commonly used attribute: the name + the telephone, can expand itself when needed.    cnmutablecontact * contact = [[Cnmutablecontact alloc]init];    Contact.givenname = name?:@ "DefaultName";    Cnlabeledvalue *phonenumber = [Cnlabeledvalue labeledvaluewithlabel:cnlabelphonenumbermobile value:[CNPhoneNumber phonenumberwithstringvalue:phone?:@ "10086"];    Contact.phonenumbers = @[phonenumber];        Add the object to the request    cnsaverequest * saverequest = [[Cnsaverequest alloc]init];    [Saverequest addcontact:contact Tocontainerwithidentifier:nil];        Execution Request    Cncontactstore * store = [[Cncontactstore alloc]init];    [Store Executesaverequest:saverequest Error:nil];}

v. My demo

Because the classes and enumerations used in different versions are not the same, I'm going to set up a uniform, and I'll handle the judgments between versions in my manager. Finally open up the unified API, as long as the introduction of the header file SXAddressBookManager.h can use these common interface.

① Check the current state, there are two APIs

-(void) checkstatus1{    sxaddressbookauthstatus status = [[Sxaddressbookmanager manager]getauthstatus];    if (status = = ksxaddressbookauthstatusnotdetermined) {        [[Sxaddressbookmanager manager]askuserwithsuccess:^{            NSLog (@ "Click to agree");        } failure:^{            NSLog (@ "Click to reject");        }];    } else if (status = = ksxaddressbookauthstatusauthorized) {        NSLog (@ "already has permission");    } else{        NSLog (@ "no Permissions");}    }
-(void) checkstatus2{    [[Sxaddressbookmanager manager]checkstatusanddosomethingsuccess:^{        NSLog (@ "already has permission, Do the related operation, can do the reading directory and other Operations ");    } failure:^{        NSLog (@ "Do not get permission, do related operations, can do the pop-up query and other operations");}    ];

② pop-up Selection window, click on the callback selected information

-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *) event{    [[Sxaddressbookmanager Manager]presentpageontarget:self chooseaction:^ (sxpersoninfoentity *person) {        NSLog (@ "%@---%@", Person.fullname,person.phonenumber);}    ];}

③ get the entire address book information

Self.personentityarray = [[Sxaddressbookmanager Manager]getpersoninfoarray];

④ write a message to the Address Book

[[Sxaddressbookmanager manager]creatitemwithname:@ "Lexus-Beijing advisory Phone" phone:@ "010-88657869"];

The demo address is

Https://github.com/dsxNiubility/SXEasyAddressBook

Here wrote I said that three points commonly used, if later some just need, will continue to add. Tung Platinum Blog Park.

iOS Address Book integration, compatible with iOS789 notation, with demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.