OC通讯录选择封装

OC通讯录选择封装

OC通讯录选择封装

ContactsService.h代码

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
//block返回选中的通讯里名字和电话
typedef void(^ChoseContacts)(NSString *name,NSString *phone);
@interface ContactsService : NSObject
@property(nonatomic,copy)ChoseContacts contacts;
/*
单例
*/
+(ContactsService *)sharedContactsService;
/**
打开系统通讯录
*/
-(void)showContactsServiceWithVC:(UIViewController *)nav; @end

ContactsService.m代码

#import "ContactsService.h"
#import <ContactsUI/ContactsUI.h>
@interface ContactsService ()<CNContactPickerDelegate>
{
CNContactPickerViewController *_contactPickerViewController;
}
@end @implementation ContactsService
static ContactsService *contacts; +(ContactsService *)sharedContactsService{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
contacts = [ContactsService new];
});
return contacts;
} -(void)showContactsServiceWithVC:(UIViewController *)nav{
_contactPickerViewController = [[CNContactPickerViewController alloc] init];
_contactPickerViewController.delegate = self; [nav presentViewController:_contactPickerViewController animated:YES completion:nil];
} // 如果实现该方法当选中联系人时就不会再出现联系人详情界面, 如果需要看到联系人详情界面只能不实现这个方法,
#pragma mark CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
[self printContactInfo:contact];
[_contactPickerViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
[_contactPickerViewController dismissViewControllerAnimated:YES completion:nil];
} - (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);
if(self.contacts){
self.contacts([NSString stringWithFormat:@"%@%@",familyName,givenName], phonNumber.stringValue);
}
break;
}
}
@end

使用:

 ContactsService *contacts = [ContactsService sharedContactsService];
contacts.contacts = ^(NSString *name, NSString *phone) {
NSString *str = [NSString stringWithFormat:@"选中的名字:%@ 电话:%@",name,phone];
UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"通讯里" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[aler show];
};
[contacts showContactsServiceWithVC:self];
上一篇:Javascript高级编程学习笔记(4)—— JS中的数据类型(2)


下一篇:记录一次线上bug