Get your phone's contact list and call

Source: Internet
Author: User

To get a list of contacts in your phone, you need to use the framework provided to us by the system: Addressbook.framework,

1. Import the framework;

2. CV model and manager:

Model:

. h

#import <Foundation/Foundation.h>@interface**phone; + (Instancetype) Contactwithitem: (ID) item; -(Instancetype) Initwithitem: (ID) item; @end

. m

#import "Contact.h"#import<AddressBook/AddressBook.h>@implementation Contact+ (Instancetype) Contactwithitem: (ID) item{return[Contact Alloc] initwithitem:item];}-(Instancetype) Initwithitem: (ID) item{ Self=[Super Init]; if(self) {nsstring*temfirstname = (__bridge NSString *) Abrecordcopyvalue ((__bridge abrecordref) (item), kabpersonfirstnameproperty); NSString*temlastname = (__bridge NSString *) Abrecordcopyvalue ((__bridge abrecordref) (item), kabpersonlastnameproperty); Abmultivalueref Tempphones=Abrecordcopyvalue (__bridge abrecordref) (item), kabpersonphoneproperty); Self.name= [NSString stringWithFormat:@"%@%@", Temlastname?temfirstname:@"", Temfirstname?temlastname:@""]; Self.phone= (__bridge NSString *) Abmultivaluecopyvalueatindex (Tempphones,0); }        returnSelf ;}@end

Managers:

. h

#import <Foundation/Foundation.h>@interface  contactmanger:nsobject-( Instancetype) Initwitharray: (Nsarray *) contacts; -(Nsdictionary *) Contactswithgroup; @end

. m

#import "ContactManger.h"#import "Contact.h"@interfaceContactmanger () @property (nonatomic, strong) Nsarray*mycontacts, @property (nonatomic, strong) Nsmutabledictionary*Contactsdic;@end@implementationContactmanger+ (NSString *) Phonetic: (NSString *) sourcestring{nsmutablestring*source =[sourcestring mutablecopy];    Cfstringtransform ((__bridge cfmutablestringref) source, NULL, Kcfstringtransformmandarinlatin, NO);    Cfstringtransform ((__bridge cfmutablestringref) source, NULL, Kcfstringtransformstripdiacritics, NO); returnsource;}-(Instancetype) Initwitharray: (Nsarray *) contacts{ Self=[Super Init]; if(self) {_mycontacts=contacts; }        returnSelf ;}-(Nsdictionary *) contactswithgroup{ for(IDIteminch_mycontacts) { Contact*people =[Contact Contactwithitem:item]; if(! [People.name isequaltostring:@""]) {nsstring*nameenglish =[Contactmanger Phonetic:people.name]; Nameenglish=[Nameenglish capitalizedstring]; Unichar k= [Nameenglish Characteratindex:0]; if(! (k >='A'&& k <='Z') ) {k='#'; } nsstring*key = [NSString stringWithFormat:@"%c", K]; Nsmutablearray*ARRAYGROUPK =[Self.contactsdic Objectforkey:key]; if(!ARRAYGROUPK) {ARRAYGROUPK= [[Nsmutablearray alloc]initwithcapacity:5];                                [ARRAYGROUPK Addobject:people]; if(Nil = =self.contactsdic) {self.contactsdic= [[Nsmutabledictionary alloc]initwithcapacity:5];                                            } [Self.contactsdic setobject:arraygroupk Forkey:key]; }Else{[ARRAYGROUPK addobject:people]; }        }                    }                returnSelf.contactsdic;}@end

Next in the VC inside the code implementation is as follows:

#import "RootViewController.h"#import "MBProgressHUD.h"#import<AddressBook/AddressBook.h>#import "Contact.h"#import "ContactManger.h"#import "LzwTableViewCell.h"@interfaceRootviewcontroller () <uitableviewdelegate, Uitableviewdatasource, uialertviewdelegate>@property (nonatomic, strong) UITableView*TableView, @property (nonatomic, assign) Abaddressbookref addressbook; @property (nonatomic, Strong) Contactmanger *Contactmanager, @property (nonatomic, strong) Nsdictionary*contactsdic; @property (nonatomic, copy) Nsarray*keys;@end@implementationRootviewcontroller- (void) viewdidload {[Super viewdidload]; //Do any additional setup after loading the view.[self Creattableview];}#pragmaMark--Create a form-(void) creattableview{Self.tableview=({UITableView*tableview =[[UITableView alloc]initwithframe:[[uiscreen mainscreen]bounds] style:uitableviewstyleplain]; TableView.Delegate=Self ; Tableview.datasource=Self ; Tableview.backgroundcolor=[Uicolor Lightgraycolor];        [TableView Setseparatorstyle:uitableviewcellseparatorstylenone];        [Self.view Addsubview:tableview];    TableView;        }); //Register Cell[Self.tableview Registerclass:[lzwtableviewcellclass] Forcellreuseidentifier:@"Cell"];    [Mbprogresshud ShowHUDAddedTo:self.view Animated:yes]; //Check Authorization status[self checkaddressbookauthorizationstatus]; }#pragmaMark-table View Data source-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{return[Self.keys Count];}-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{nsstring*key =[Self.keys objectatindex:section]; Nsarray* Array =[Self.contactsdic Objectforkey:key]; return[array count];}-(nsstring*) TableView: (UITableView *) TableView titleforheaderinsection: (nsinteger) section{returnself.keys[section];}-(nsarray*) Sectionindextitlesfortableview: (UITableView *) tableview{returnSelf.keys;}-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{Lzwtableviewcell*cell = [TableView dequeuereusablecellwithidentifier:@"Cell"]; NSString*key =[Self.keys objectAtIndex:indexPath.section]; Contact*people =[[Self.contactsdic Objectforkey:key] objectAtIndex:indexPath.row]; Cell.labelName.text=People.name; Cell.labelNumber.text=People.phone; returncell;}-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{return  -;}/** * Authorization Status of Address Book*/- (void) checkaddressbookauthorizationstatus{//InitializeSelf.addressbook =abaddressbookcreatewithoptions (nil, nil); if(kabauthorizationstatusauthorized = =Abaddressbookgetauthorizationstatus ()) {NSLog (@"has been authorized"); } abaddressbookrequestaccesswithcompletion (Self.addressbook,^(BOOLgranted, cferrorref error) {Dispatch_async (Dispatch_get_main_queue (),^{            if(Error) {[Mbprogresshud hideHUDForView:self.view animated:yes]; NSLog (@"Error:%@", error); }Else if(!granted)                {[Mbprogresshud hideHUDForView:self.view animated:yes]; Uialertview*alert = [[Uialertview alloc] Initwithtitle:@"Authorization Denied"message:@"Set permissions in Setting>genearl>privacy."                                                               Delegate: Nil Cancelbuttontitle:nil Otherbuttontitles:@"OK", nil];            [Alert show]; }Else{                //Restore AbaddressbookrefAbaddressbookrevert (Self.addressbook); Self.contactmanager= [[Contactmanger alloc] Initwitharray: (__bridge Nsarray *) (Abaddressbookcopyarrayofallpeople (Self.addressbook))]; Self.contactsdic=[Self.contactmanager Contactswithgroup]; Self.keys=[[Self.contactsdic AllKeys] Sortedarrayusingselector: @selector (compare:)];                                [Mbprogresshud HideHUDForView:self.view Animated:yes];                [Self.tableview Setseparatorstyle:uitableviewcellseparatorstylesingleline];            [Self.tableview Reloaddata];    }        });    }); }- (void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{NSString*key =[Self.keys objectAtIndex:indexPath.section]; Contact*people =[[Self.contactsdic Objectforkey:key] objectAtIndex:indexPath.row]; Uialertview*alert =[[Uialertview alloc] InitWithTitle:people.name Message:people.phon EDelegate: Self cancelbuttontitle:@"Cancel"Otherbuttontitles:@"Call", nil]; [Alert show];}#pragmamark-uialertviewdelegate-(void) Alertview: (Uialertview *) Alertview Clickedbuttonatindex: (nsinteger) buttonindex{uiapplication*app =[UIApplication sharedapplication]; if(Buttonindex = =1) {[App Openurl:[nsurl urlwithstring:[nsstring stringWithFormat:@"tel://%@", Alertview.message]]; }}@end

This allows you to get contacts and call functions for your local contacts, as follows:

Complete!!!

Get your phone's contact list and call

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.