iOS framework-using Address Book

Source: Internet
Author: User

One, why it is important to support Address Book:

When developing iOS software, it is linked to the user's mobile life. Users go everywhere with mobile devices, which can be said that mobile devices and the user's personal life (from the calendar to the personal album) is a solidarity. In this mobile life, the Address Book occupies an important position. Apps can use the contact database to determine whether a user has a friend registered for the service: Analyze the contact's e-mail address or phone number, and automatically add the contact as a friend. Apps can also use the contact list to automatically fill in email addresses or phone numbers, or let users share contact information with friends via Bluetooth. There are countless reasons why apps need access to user contacts.

Note:

unless you have a good reason to do so, it is important that you do not access the contact database, because there is nothing more than disclosing privacy that allows users to resolutely abandon your app.
Ii. Use of Address Book

To use the Address Book framework, you need to first import the two frames for your phonebook into your project: Addressbookui.framework and Addressbook.framework. The former provides a graphical user interface for selecting, editing, and displaying contacts, which allows you to interact with contact data. Then import the header file in the related class, as follows:

#import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h>
First, I created the properties of two classes in my project: AddressBook and Addressbookentryarray
@property (nonatomic, assign) Abaddressbookref addressbook; @property (nonatomic, strong) Nsmutablearray * Addressbookentryarray;

Addressbookentryarray is used to store an array of address book entries in the acquired system.

Note:

The cost of copying the address book
to memory is extremely high, so you should minimize the number of such operations.
When using the address book, we should get access to the phonebook in the phone:
Request access Rights Abaddressbookrequestaccesswithcompletion (_addressbook, ^ (bool greanted, cferrorref error) {    // Greanted for Yes indicates user permission, otherwise the    if (!greanted) {        NSLog (@ "not granted permission") is not allowed;}    );
Next, create a reference to the Address book:
Cferrorref error = null;//creates a reference to the address book _addressbook = abaddressbookcreatewithoptions (nil, &error);
When creating the Address book reference, it is better to use abaddressbookcreatewithoptions this method, the originalAbaddressbookcreate has been voided.

Ab_extern abaddressbookref abaddressbookcreatewithoptions (cfdictionaryref options, cferrorref* error) __OSX_ Available_starting (__MAC_NA,__IPHONE_6_0); Ab_extern abaddressbookref abaddressbookcreate (void) __osx_available_but_deprecated (__mac_na,__mac_na,__iphone_2_ 0,__IPHONE_6_0);
As you can see from the code above,the version supported by Abaddressbookcreate is iOS 2.0 to iOS 6.0 and should be used after developing iOS 6.0 system abaddressbookcreatewithoptions to createA reference to the Address Book.

_addressbookentryarray = (__bridge Nsmutablearray *) abaddressbookcopyarrayofallpeople (_addressBook);

Once you've created a reference to your address book, you'll copy the contacts from your phonebook to the array Addressbookentryarray , where I've copied all of the contacts and other copies of the API documentation for you. Before getting all the contacts need to consider the address book is empty, in this case give the user a good hint, let the user know that the app does not crash crashes, here I used an alert pop-up window to simply display the message.

if (Abaddressbookgetpersoncount (_addressbook) = = 0) {    Uialertview *alertview = [[Uialertview alloc] initwithtitle:@ "Contact man-made empty"                                                        message:@ ""                                                       delegate:nil                                              cancelbuttontitle:@ "to determine"                                              otherbuttontitles:nil ";    [Alertview show];}
After reading the contact information in the Address book, the data obtained here is displayed in a tableviewcontroller.

iii. reading data from the address book

each entry that is read into the Addressbookentryarray array is a abrecordref, and the single-valued data can be read using the method Abrecordcopyvalue method:

Abrecordref record = (__bridge abrecordref) ([_addressbookentryarray objectAtIndex:indexPath.row]); Cfstringref firstName = Abrecordcopyvalue (record, kabpersonfirstnameproperty); Cfstringref lastName = Abrecordcopyvalue (record, kabpersonlastnameproperty);
The FirstName and LastName of the contacts are available here.

all the single-valued properties of the Abrecordref are shown in the following table:

Property name Description
Kabpersonfirstnameproperty Name
Kabpersonlastnameproperty Name
Kabpersonmiddlenameproperty Middle name or written
Kabpersonprefixproperty
Name Prefixes (Mr, Ms, Dr.)
Kabpersonsuffixproperty
Name suffix (MD, Jr, Sr.)
Kabpersonnicknameproperty
Alias
Kabpersonfirstnamephoneticproperty
The pronunciation of the name
Kabpersonlastnamephoneticproperty
The pronunciation of a surname
Kabpersonmiddlenamephoneticproperty
Middle name Pronunciation
Kabpersonorganizationproperty
Company or organization
Kabpersonjobtitleproperty
Duties
Kabpersondepartmentproperty
Department
Kabpersonemailproperty
e-mail address
Kabpersonbirthdayproperty
Cfdate format for birthdays, free to bridge to NSDate
Kabpersonnoteproperty
Note
Kabpersoncreationdateproperty
Date of creation of the cfdate format
Kabpersonmodificationdateproperty
Last modified date in cfdate format
Iv. Reading multi-valued data from the address Book

Abmultivalueref is required when reading multi-valued data from the address book, such as phone numbers, e-mail addresses, and street addresses. Here's how to manipulate addresses in Address book (the address is a very special multivalued data, because a dictionary type of data is taken out):

  the use of Address book addresses Abmultivalueref Addressmulti = Abrecordcopyvalue (record, kabpersonaddressproperty); NSString *address = nil; NSString *street = nil; NSString *city = nil; NSString *state = nil; NSString *zip = nil;if (Abmultivaluegetcount (Addressmulti) > 0) {    nsdictionary *addressdictionary = (__bridge NSDi Ctionary *) (Abmultivaluecopyvalueatindex (addressmulti, 0));    Street = [addressdictionary objectforkey: (NSString *) Kabpersonaddressstreetkey];    City = [Addressdictionary objectforkey: (NSString *) Kabpersonaddresscitykey];    state = [Addressdictionary objectforkey: (NSString *) Kabpersonaddressstatekey];    Zip = [Addressdictionary objectforkey: (NSString *) Kabpersonaddresszipkey];} address = [NSString stringWithFormat: @ "%@%@%@%@", Street, city, state, zip];
As you know from the API, the address is a dictionary-type value. First, the address is taken out, and then converted into a dictionary, using the corresponding key in the API to obtain the corresponding data.

The components of the address are shown in the following table:

Properties Description
Kabpersonaddressstreetkey
Street name and number (including room numbers)
Kabpersonaddresscitykey
City Name
Kabpersonaddressstatekey
Two-word Fuzhou name or full state name
Kabpersonaddresszipkey
Zip code (5-bit or 9-digit)
Kabpersonaddresscountrykey
The full country name
Kabpersonaddresscountrycodekey
Two words country the code
V. Use of Address tags

The

uses the index number of the phone number after it gets to the phone number through a multivalued value. Although the phone number index is useful for developers, it is meaningless for the user, so use the address tag to get the label used by the contact. To get the label for a multivalued reference, you first need to call abmultivaluecopylabelatindex . When this function is called, the parameter used is the same as when the value of the multivalued object is obtained. This function returns a non-localized string such as: _$!<mobile>!$_. Although this string is more useful than the peso quotes, it is still less appropriate to display to the user. To get a string that the user can see, the returned label needs to be localized. To do this, call abaddressbookcopylocalizedlabel , and will just return the cfstringref as a parameter. In the code I get the label of the phone number and output it to the background:

  methods for reading multiple values abmultivalueref phonenumbers = Abrecordcopyvalue (record, kabpersonphoneproperty); Abmultivaluegetcount (Phonenumbers) > 0) {for    (int i = 0; i < Abmultivaluegetcount (phonenumbers); i++) {//    Two parameters are the type of get phone number, for example: mobile phone, home phone, etc. (Address Book label)        NSLog (@ "%@ [%@]", Abmultivaluecopyvalueatindex (Phonenumbers, i), Abaddressbookcopylocalizedlabel (Abmultivaluecopylabelatindex (phonenumbers, i)));}    }
Vi. Contact Selector

The contact selector creates a similar interface as the contact selector in the system's built-in address book. First this class needs to follow the protocol abpeoplepickernavigationcontrollerdelegate and then create a selection controller using the following code.

Abpeoplepickernavigationcontroller *picker = [[Abpeoplepickernavigationcontroller alloc] init]; Picker.peoplepickerdelegate = self; [Self Presentviewcontroller:picker animated:yes completion:nil];

When the selector is created, there are three delegate methods, which are appropriate when the user interacts with the contact selector. The first approach is to respond to the user Cancel button:

-(void) Peoplepickernavigationcontrollerdidcancel: (Abpeoplepickernavigationcontroller *) PeoplePicker {        [self Dismissviewcontrolleranimated:yes Completion:nil];}
The second delegate method is to tell the contact selector that you do not want the user to select the specific properties of the contact, that is, the user cannot view the details of the contact through the contact selector. When a user selects a contact, the contact selector is automatically dismiss out.
After this method selects a contact, you cannot jump to the detail page, that is, the details cannot be read-(void) Peoplepickernavigationcontroller: (Abpeoplepickernavigationcontroller *) Peoplepicker Didselectperson: (abrecordref) person {    NSLog (@ ' You have selected:%@ ', abrecordcopyvalue (person, Kabpersonfirstnameproperty));}
After the third delegate method is implemented, the user can view the details of the contact.
You can get contact details-(void) Peoplepickernavigationcontroller: (Abpeoplepickernavigationcontroller *) peoplepicker Didselectperson: (abrecordref): (Abpropertyid) Property identifier: (Abmultivalueidentifier) identifier {        NSLog (@ "Person:%@, property:%i, identifier:%i", person, property, identifier);}

Here we can also customize the contact selector to enter the detailed page after the content can be accessed, after creating the contact selector, add the following code after the user enters the detailed page can only view the contact's phone number:

Picker.displayedproperties = [Nsarray arraywithobject: [NSNumber Numberwithint:kabpersonphoneproperty]];
Vi. editing and viewing contacts using Abpersonviewcontroller

In most cases, the built-in Address Book user interface is used to display or edit contacts. In this code, the contact information is displayed in a TableView, and when the cell is selected, it jumps to a Abpersonviewcontroller page to view the contact details.

Abpersonviewcontroller *personviewcontroller = [[Abpersonviewcontroller alloc] init]; Abrecordref record = (__bridge abrecordref) ([_addressbookentryarray objectAtIndex:indexPath.row]); Personviewcontroller.personviewdelegate = Self;personviewcontroller.displayedperson = record; personviewcontroller.allowsediting = Yes;personviewcontroller.allowsactions = NO; [Self.navigationcontroller Pushviewcontroller:personviewcontroller Animated:yes];

The Allowsediting property here is whether the contact information can be edited after the settings have been entered into the detail page.

Vii. using Abnewpersonviewcontroller to create a new contact
Abnewpersonviewcontroller *newpersoncontroller = [[Abnewpersonviewcontroller alloc] init]; Newpersoncontroller.newpersonviewdelegate = self; [Self.navigationcontroller Pushviewcontroller:newpersoncontroller Animated:yes];

when a user saves a contact, a delegate method is called. In this method, after determining that the returned contact object is valid, Abaddressbookaddrecord and Abaddressbooksave are called in turn to save the contact to the Address Book.

-(void) Newpersonviewcontroller: (Abnewpersonviewcontroller *) Newpersonview Didcompletewithnewperson: (ABRECORDREF) person {    if (person) {        Cferrorref error = NULL;        Abaddressbookaddrecord (_addressbook, person, &error);        Abaddressbooksave (_addressbook, &error);        if (Error! = NULL) {            NSLog (@ "An error occurred");}    }    _addressbookentryarray = (__bridge Nsmutablearray *) abaddressbookcopyarrayofallpeople (_addressBook);    [Self.tableview Reloaddata];    [Self.navigationcontroller Poptorootviewcontrolleranimated:yes];}

iOS framework-using Address Book

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.