4 ways to get a list of IOS _ios

Source: Internet
Author: User

This example for you to share the iOS access to the Address Book 4 ways for Everyone to refer to, the specific content as follows

Working with scenes

Some apps use phone numbers to recommend friends, such as Weibo, Alipay

First, the client will get all the phone number in the address Book and then submit the mobile phone number to the app server, the server will look for each cell phone number corresponding to the app account, such as QQ number returned to the client, and then the client based on the server returned to the list of accounts to recommend friends.

Get Contact Way

Programme I: Addressbookui.framework framework

Provides a contact list interface, contact details interface, add contact interface, etc.
Generally used to select contacts

Programme II: Addressbook.framework framework:
No UI interface, you need to build your own contact interface
Pure C language API, just get contact data
Most data types are core Foundation
Starting from iOS6, you need to get the user's authorization to access the Address Book

Programme III: Third-party framework: Rhaddressbook
To encapsulate a addressbook.framework

Programme IV: iOS9.0 The latest Address Book framework
Contactsui.framework: Alternatives to option 1, features: object-oriented, simple to use, interface
Contacts.framework: Alternatives to Option 2, features: object-oriented, simple to use, five interfaces

programme I: addressbookui.framework

Implementation steps:

1. Create a controller to select a contact
2. Set up Agent: Used to receive user-selected contact information
3. Pop-up Contact Controller
4. Implementing the Proxy method
5. Get contact information in the corresponding proxy method

Addressbook.frame implementation steps:

1. Request for authorization
2. Determine the status of authorization to continue if authorized, if not authorized to prompt the user
3. Create the Address Book object
4. Get all the contacts from the Address Book
5. Iterate through all the contacts
6. Releasing objects that are no longer in use

Addreesbook.framework Specific implementation:

1. Appdelegate request Authorization when application starts

#import "AppDelegate.h"
#import <AddressBook/AddressBook.h>

@interface appdelegate ()

@end

@ Implementation Appdelegate

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: ( Nsdictionary *) launchoptions {
 //Override point for customization after application launch.

 [Self requestauthorizationaddressbook];
 Return YES
}


-(void) Requestauthorizationaddressbook {
 //Judge whether authorization
 abauthorizationstatus authorizationstatus = Abaddressbookgetauthorizationstatus ();
 if (Authorizationstatus = = kabauthorizationstatusnotdetermined) {
  //Request Authorization
  abaddressbookref addressbookref = Abaddressbookcreate ();
  Abaddressbookrequestaccesswithcompletion (Addressbookref, ^ (bool granted, cferrorref error) {
   if (granted) {// Authorization succeeded

   } else {  //Authorization failed
    NSLog (@) Authorization failed! ");
   }
  });
 }
}
@end

2. iOS10 needs to be configured in Info.plist nscontactsusagedescription

<key>NSContactsUsageDescription</key>
<string> request access to address Book </string> 

3. Viewcontroller

#import "ViewController.h" #import <AddressBook/AddressBook.h> @interface Viewcontroller () @end @implementation

Viewcontroller-(void) viewdidload {[Super viewdidload];} -(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *) Event {//1. Interpretation Authorization Abauthorizationstatus AUT
 Horizationstatus = Abaddressbookgetauthorizationstatus ();
  if (authorizationstatus!= kabauthorizationstatusauthorized) {NSLog (@ "not authorized");
 Return }//2.
 Get all contacts Abaddressbookref Addressbookref = Abaddressbookcreate ();
 Cfarrayref arrayref = abaddressbookcopyarrayofallpeople (addressbookref);
 Long Count = Cfarraygetcount (ARRAYREF);

  for (int i = 0; i < count; i++) {//Get the reference to the contact object abrecordref people = Cfarraygetvalueatindex (arrayref, i);

  Gets the current contact name NSString *firstname= (__bridge NSString *) (Abrecordcopyvalue (People, kabpersonfirstnameproperty));
  Gets the current contact last name NSString *lastname= (__bridge NSString *) (Abrecordcopyvalue (People, kabpersonlastnameproperty)); NSLog (@"--------------------------------------------------");

  NSLog (@ "firstname=%@, lastname=%@", FirstName, LastName);
  Gets the phone array of the current contact Nsmutalearray *phonearray = [[Nsmutablearray alloc]init];
  Abmultivalueref phones = Abrecordcopyvalue (people, kabpersonphoneproperty); For (Nsinteger j=0 j<abmultivaluegetcount (phones); J + +) {nsstring *phone = (__bridge NSString *) (ABMULTIVALUECOPYV
   Alueatindex (Phones, j));
   NSLog (@ "phone=%@", phone);
  [Phonearray Addobject:phone];
  //Get the current contact's mailbox note is an array nsmutablearray *emailarray = [[Nsmutablearray alloc]init];
  Abmultivalueref emails= Abrecordcopyvalue (People, kabpersonemailproperty); For (Nsinteger j=0 j<abmultivaluegetcount (emails); j + +) {nsstring *email = (__bridge NSString *) (ABMULTIVALUECOPYV
   Alueatindex (Emails, j));
   NSLog (@ "email=%@", email);
  [Emailarray Addobject:email];
  //Get the current contact middle name NSString *middlename= (__bridge nsstring*) (Abrecordcopyvalue (People, kabpersonmiddlenameproperty)); Gets the name prefix NS for the current contactString *prefix= (__bridge nsstring*) (Abrecordcopyvalue (People, kabpersonprefixproperty));

  Gets the name suffix of the current contact NSString *suffix= (__bridge nsstring*) (Abrecordcopyvalue (People, kabpersonsuffixproperty));

  Gets the nickname of the current contact NSString *nickname= (__bridge nsstring*) (Abrecordcopyvalue (People, kabpersonnicknameproperty)); Gets the name of the current contact Pinyin nsstring *firstnamephoneic= (__bridge nsstring*) abrecordcopyvalue (People,

  Kabpersonfirstnamephoneticproperty)); Gets the surname pinyin of the current contact NSString *lastnamephoneic= (__bridge nsstring*) abrecordcopyvalue (People,

  Kabpersonlastnamephoneticproperty)); Gets the middle name of the current contact Pinyin nsstring *middlenamephoneic= (__bridge nsstring*) abrecordcopyvalue (People,

  Kabpersonmiddlenamephoneticproperty)); Gets the company NSString *organization= (__bridge nsstring*) of the current contact (Abrecordcopyvalue (People, Kabpersonorganizationproperty))

  ;

  Gets the position of the current contact NSString *job= (__bridge nsstring*) (Abrecordcopyvalue (People, kabpersonjobtitleproperty)); Get the Department of the current contact NSString *department= (__bridge nsstring*) (ABrecordcopyvalue (People, kabpersondepartmentproperty));

  Gets the current contact's birthday nsstring *birthday= (__bridge nsdate*) (Abrecordcopyvalue (People, kabpersonbirthdayproperty));

  Gets the comments for the current contact NSString *notes= (__bridge nsstring*) (Abrecordcopyvalue (People, kabpersonnoteproperty)); Get time to create the current contact note is nsdate nsdate *creattime= (__bridge nsdate*) abrecordcopyvalue (People,

  Kabpersoncreationdateproperty)); Gets the time when the current contact was modified NSDate *altertime= (__bridge nsdate*) (Abrecordcopyvalue (People, Kabpersonmodificationdateproperty)

  );
  Get Address Abmultivalueref = Abrecordcopyvalue (people, kabpersonaddressproperty); for (int j=0; J<abmultivaluegetcount (addresses); J + +) {//address type NSString *type = (__bridge NSString *) (ABMULTIVALUEC
   Opylabelatindex (Address, j));
   Nsdictionary * Tempdic = (__bridge nsdictionary *) (Abmultivaluecopyvalueatindex (address, j)); Address strings that can be formatted nsstring *adress = [NSString stringwithformat:@ "Country:%@\n Province:%@\n City:%@\n Street:%@\n ZIP Code:%@", [Temdic Valueforkey: (nsstring*) KABpersonaddresscountrykey],[tempdic Valueforkey: (nsstring*) kabpersonaddressstatekey],[tempdic ValueForKey: ( nsstring*) kabpersonaddresscitykey],[tempdic Valueforkey: (nsstring*) Kabpersonaddressstreetkey],[tempdic
  Valueforkey: (nsstring*) Kabpersonaddresszipkey]];

  //Get the current contact avatar Picture NSData *userimage= (__bridge nsdata*) (Abpersoncopyimagedata (people));
  Get current Contact Anniversary Nsmutablearray *datearr = [[Nsmutablearray alloc]init];
  Abmultivalueref dates= Abrecordcopyvalue (People, kabpersondateproperty); For (Nsinteger j=0 j<abmultivaluegetcount (dates); J + +) {//Get anniversary date nsdate *data = (__bridge nsdate*) (abmultivalue
   Copyvalueatindex (dates, j));
   Get Anniversary name NSString *str = (__bridge nsstring*) (Abmultivaluecopylabelatindex (dates, j));
   Nsdictionary *tempdic = [nsdictionary dictionarywithobject:data forkey:str];
  [Datearr Addobject:tempdic];

 }}} @end

4. Operating Results

Third-party framework: Rhaddressbook

Https://github.com/heardrwt/RHAddressBook

The framework uses MRC to manage memory, and if you drag the source code directly into it, you need to set up a compilation tag for each file:-fno-objc-arc, set up also will be an error, the project used some methods too old, many do not support, so this way is not adopted; You can play the project as a static library, or you can drag the project directly into your own project as a dependent

1. Drag rhaddressbook.xcodeproj directly into the project

2. Add target dependencies and link Binary with libraries

3.Build settings-> Other Linker Flags:-OBJC

Error for resolving system classification cannot find method

4.IOS10 needs to be configured in Info.plist nscontactsusagedescription

<key>NSContactsUsageDescription</key>
<string> request access to address Book </string>  

Requesting access to the Address book when app starts

#import "AppDelegate.h"
#import <RHAddressBook/RHAddressBook.h>

@interface appdelegate ()

@end

@implementation appdelegate

-(BOOL) Application: (UIApplication *) application Didfinishlaunchingwithoptions: (nsdictionary *) launchoptions {
  //Override point for customization after Application launch.

  [Self requestauthorizationforaddressbook];
  Return YES
}

-(void) Requestauthorizationforaddressbook {
  Rhaddressbook *ab = [[Rhaddressbook alloc] init];
  if ([rhaddressbook authorizationstatus] = = rhauthorizationstatusnotdetermined) {

    [ab requestauthorizationwithcompletion:^ (bool Granted, Nserror *error) {
      if (granted) {

      } else {
        NSLog (@) Request authorization Reject ");}}
    ];
  }
@end

Get information for all contacts: name, cell phone number, etc.

#import "ViewController.h" #import <RHAddressBook/RHAddressBook.h> #import <rhaddressbook/addressbook.h

> @interface viewcontroller () @end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload];} -(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *) Event {Rhaddressbook *addressbook = [[RHAdd
  Ressbook alloc] init];
    if ([Rhaddressbook authorizationstatus]!= rhauthorizationstatusauthorized) {NSLog (@ "not authorized");
  Return
  } nsarray *peoplearray= addressbook.people;
    for (int i = 0; i < Peoplearray.count i++) {Rhperson *people = (Rhperson *) peoplearray[i];

    NSLog (@ "%@", people.name);
    Rhmultistringvalue *phonenumbers = people.phonenumbers;
      for (int i = 0; i < Phonenumbers.count i++) {nsstring* label= [phonenumbers labelatindex:i];

      nsstring* value= [Phonenumbers valueatindex:i];
    NSLog (@ "label=%@, value=%@", label, value); } NSLog (@ "----------------------------------------------");

 }} @end

Run Result:

Contactsui.framework

#import "ViewController.h" #import <ContactsUI/ContactsUI.h> @interface Viewcontroller () <

  cncontactpickerdelegate> @end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload];
  Cncontactpickerviewcontroller *contactpickerviewcontroller = [[Cncontactpickerviewcontroller alloc] init];

  Contactpickerviewcontroller.delegate = self;
[Self Presentviewcontroller:contactpickerviewcontroller animated:yes completion:nil]; ///If the contact details interface is not present when the method is implemented for the contact, if you need to see the contact details interface only do not implement this method,-(void) Contactpicker: (Cncontactpickerviewcontroller *)

  Picker didselectcontact: (cncontact *) Contact {NSLog (@ "Call---------------------------------when selected)";
[Self printcontactinfo:contact]; ///Select more than one contact-(void) Contactpicker: (Cncontactpickerviewcontroller *) Picker didselectcontacts: (nsarray<cncontact *> *) Contacts {for (cncontact *contact in Contacts) {NSLog (@ "================================================")
    ;
  [Self printcontactinfo:contact]; }
}

-(void) Printcontactinfo: (cncontact *) Contact {nsstring *givenname = contact.givenname;
  NSString *familyname = contact.familyname;
  NSLog (@ "givenname=%@, familyname=%@", givenname, familyname);
  Nsarray * phonenumbers = contact.phonenumbers;
    For (Cnlabeledvalue<cnphonenumber*>*phone in phonenumbers) {nsstring *label = Phone.label;
    Cnphonenumber *phonnumber = (Cnphonenumber *) Phone.value;
  NSLog (@ "label=%@, value=%@", label, Phonnumber.stringvalue); }//Note: If this method is implemented, the above method cannot be implemented, and the two methods can only implement one//-(void) Contactpicker: (Cncontactpickerviewcontroller *) picker

 Didselectcontactproperty: (Cncontactproperty *) Contactproperty {//NSLog (called when an attribute of a contact is selected);//} @end

To run an effect when you select a single contact:

Select an interface for more than one contact:


Contact.framework

IOS10 needs to be configured in Info.plist nscontactsusagedescription

<key>NSContactsUsageDescription</key>
<string> request access to address Book </string>  

Request authorization upon application startup:

#import "AppDelegate.h"
#import <Contacts/Contacts.h>

@interface appdelegate ()

@end

@ Implementation Appdelegate


-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: ( Nsdictionary *) launchoptions {
  //Override point for customization after application launch.

  [Self requestauthorizationforaddressbook];
  Return YES
}

-(void) Requestauthorizationforaddressbook {
  Cnauthorizationstatus authorizationstatus = [Cncontactstore Authorizationstatusforentitytype:cnentitytypecontacts];
  if (Authorizationstatus = = cnauthorizationstatusnotdetermined) {
    Cncontactstore *contactstore = [[CNContactStore ALLOC] init];
    [Contactstore requestaccessforentitytype:cnentitytypecontacts completionhandler:^ (BOOL Granted, NSError * _Nullable Error) {
      if (granted) {

      } else {
        NSLog (@ "Authorization failed, error=%@", error);

}} @end

Get Address Book information

#import "ViewController.h" #import <Contacts/Contacts.h> @interface Viewcontroller () @end @implementation VIEWC

Ontroller-(void) viewdidload {[Super viewdidload]; }-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *) event {Cnauthorizationstatus Authorizati
  Onstatus = [Cncontactstore authorizationstatusforentitytype:cnentitytypecontacts];
  if (Authorizationstatus = = cnauthorizationstatusauthorized) {NSLog (@ "not authorized ..."); //Get the specified field, not to get all the fields, you need to specify a specific field Nsarray *keystofetch = @[cncontactgivennamekey, Cncontactfamilynamekey, cncontactph
  Onenumberskey];
  Cncontactfetchrequest *fetchrequest = [[Cncontactfetchrequest alloc] initwithkeystofetch:keystofetch];
  Cncontactstore *contactstore = [[Cncontactstore alloc] init]; [Contactstore enumeratecontactswithfetchrequest:fetchrequest error:nil usingblock:^ (CNContact * _Nonnull Contact,
    BOOL * _nonnull stop) {NSLog (@ "-------------------------------------------------------"); Nsstring *givenname = contact.givenname;
    NSString *familyname = contact.familyname;


    NSLog (@ "givenname=%@, familyname=%@", givenname, familyname);
    Nsarray *phonenumbers = contact.phonenumbers;
      For (Cnlabeledvalue *labelvalue in phonenumbers) {nsstring *label = Labelvalue.label;

      Cnphonenumber *phonenumber = Labelvalue.value;
    NSLog (@ "label=%@, phone=%@", label, Phonenumber.stringvalue); }//*stop = YES;

Stop loop, equivalent to break;}];

 } @end

Operation Effect:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.