通讯录 与 发送邮件---iOS

通讯录

AddressBook框架

基于C语言,无法使用ARC来管理内存,需要开发者自己管理内存

ABAddressBookRef:代表通讯录对象(有更改后必须保存)
ABRecordRef:一条记录(联系人 或 群组)通过ABRecordGetRecordType()获取类型。通过ABRecordGetRecordID()获取该记录的唯一ID
ABPersonRef/ABGroupRef:联系人/群组,一般不使用,一般用:“kABPersonType”的ABRecordRef,“kABGroupType”的ABRecordRef


ABPersonCreate()        创建“kABPersonType”的ABRecordRef
ABRecordCopyValue()         获取指定属性值
ABRecordCopyCompositeName() 获取记录信息
ABRecordSetValue()  给纪录设置单值属性 。多值属性:先创建一个ABMutableMultiValueRef类型的变量,然后通过ABMultiValueAddValueAndLabel()方法依次添加属性值,最后通过ABRecordSetValue()方法设置为记录。
ABRecordRemoveValue()。 删除指定属性值。
#import "YTPersonCCViewController.h"
#import 


@interface YTPersonCCViewController ()
@property (strong,nonatomic) NSMutableArray *personArr;     // 通讯录联系人
@property (nonatomic,assign) ABAddressBookRef addressBook;  // 通讯录对象
@end


@implementation YTPersonCCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    [self setupData];
    [self setupUI];
}

// data
-(void)setupData{

    // 访问通讯录对象
    _addressBook=ABAddressBookCreateWithOptions(NULL, NULL);
    // 请求访问
    ABAddressBookRequestAccessWithCompletion(_addressBook, ^(bool granted, CFErrorRef error) {
        
        //
        if (ABAddressBookGetAuthorizationStatus()!=kABAuthorizationStatusAuthorized) {
            NSLog(@"未获得通讯录访问授权");
            return ;
        }
        // 获取 通讯录联系人
        CFArrayRef peopleArr=ABAddressBookCopyArrayOfAllPeople(_addressBook);
        _personArr=(__bridge NSMutableArray *)peopleArr;
        CFRelease(peopleArr);
    });
}

// UI
-(void)setupUI{
    UITableView *personTV=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [personTV setDelegate:self];
    [personTV setDataSource:self];
    [self.view addSubview:personTV];
    [personTV autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
}
//
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _personArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    
    // 获取到 单条 联系人记录
    ABRecordRef recordRef=(__bridge ABRecordRef)_personArr[indexPath.row];
    // name
    NSString *firstName=(__bridge NSString*)ABRecordCopyValue(recordRef, kABPersonFirstNameProperty);
    NSString *lastName=(__bridge NSString*)ABRecordCopyValue(recordRef, kABPersonLastNameProperty);
    // phone
    ABMultiValueRef phoneRef=ABRecordCopyValue(recordRef, kABPersonPhoneProperty);
    NSArray *phoneArr=(__bridge NSArray*)ABMultiValueCopyArrayOfAllValues(phoneRef);
    long phoneCount=ABMultiValueGetCount(phoneRef);
    for(int i=0;i
AddressBookUI框架
#import 

-》添加新联系人页面


    //
    ABNewPersonViewController *newPersonC=[ABNewPersonViewController new];
    newPersonC.newPersonViewDelegate=self;
    [self presentViewController:[[UINavigationController alloc]initWithRootViewController:newPersonC] animated:true completion:nil];


// ABNewPersonViewControllerDelegate
-(void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{

    if(person){
    
        NSLog(@"save success");
    }else{
        NSLog(@"cancel");
    }
    [self dismissViewControllerAnimated:true completion:nil];
}

-》查看 某联系人详情页面(根据ID)


    // 查看 某联系人(根据ID)
    ABPersonViewController *personC=[ABPersonViewController new];
    personC.personViewDelegate=self;
    ABAddressBookRef addressBook=ABAddressBookCreate();
    ABRecordRef recordRef=ABAddressBookGetPersonWithRecordID(addressBook, 1);
    personC.displayedPerson=recordRef;
    personC.allowsActions=true;
    personC.allowsEditing=true;
    [self presentViewController:[[UINavigationController alloc]initWithRootViewController:personC] animated:true completion:nil];

// ABPersonViewControllerDelegate
-(BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

    //
    if(person){
    
        NSLog(@"点击了%i属性:%@",property,(__bridge NSString*)ABRecordCopyValue(person, property));
    }
    return false;
}

-》查看联系人列表页面



    //
    ABPeoplePickerNavigationController *peoplePickerC=[ABPeoplePickerNavigationController new];
    [peoplePickerC setPeoplePickerDelegate:self];
    [self presentViewController:peoplePickerC animated:true completion:nil];



-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    //
    NSLog(@"cancel select");
}
// 实现了本方法,则下边的属性方法不再执行
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person{

    //
    if(person){
        NSLog(@"%@",(__bridge NSString*)ABRecordCopyCompositeName(person));   // 联系人  名
    }
}
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

    //
    if(person&&property){
        NSLog(@"点击了%i属性:%@",property,(__bridge NSString*)ABRecordCopyValue(person, property));
    }
}

-》添加到未知联系人

ABUnknownPersonViewControllerDelegate

    ABUnknownPersonViewController *unknowPersonC=[ABUnknownPersonViewController new];
    
    ABRecordRef recordRef=ABPersonCreate();
    // name
    ABRecordSetValue(recordRef, kABPersonFirstNameProperty, @"少林张三丰", NULL);
    ABRecordSetValue(recordRef, kABPersonLastNameProperty, @"110", NULL);
    // phone
    ABMutableMultiValueRef muValueRef=ABMultiValueCreateMutable(kABStringPropertyType);
    ABMultiValueAddValueAndLabel(muValueRef, @"130****5423", kABHomeLabel, NULL);
    ABRecordSetValue(recordRef, kABPersonPhoneProperty, muValueRef, NULL);
    //
    unknowPersonC.displayedPerson=recordRef;
    unknowPersonC.unknownPersonViewDelegate=self;
    unknowPersonC.allowsActions=true;               // 允许交互
    unknowPersonC.allowsAddingToAddressBook=true;   // 允许加入通讯录
    
    //
    CFRelease(muValueRef);
    CFRelease(recordRef);
    
    //
    [self presentViewController:[[UINavigationController alloc]initWithRootViewController:unknowPersonC] animated:true completion:nil];

-(void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person{

    if(person){
    
        //
        NSLog(@"%@ save success",(__bridge NSString*)ABRecordCopyCompositeName(person));
    }
}
-(BOOL)unknownPersonViewController:(ABUnknownPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

    //
    if(person){
        NSLog(@"选择了属性:%i  值:%@",property,(__bridge NSString*)ABRecordCopyValue(person, property));
    }
    
    return false;
}

发邮件

MFMessageComposeViewController
#import 

            //
            if([MFMessageComposeViewController canSendText]){
                MFMessageComposeViewController *messageController=[[MFMessageComposeViewController alloc]init];
                messageController.messageComposeDelegate=self;
                messageController.recipients=@[@"收件人",@"收件人2"];
                messageController.body=@"信息正文";
                if([MFMessageComposeViewController canSendSubject]){
                    messageController.subject=@"主题";
                }
                if ([MFMessageComposeViewController canSendAttachments]) {
                    // 方法1
                    // messageController.attachments=...;
                    
                    // 方法2
                    NSArray *attachmentArr= @[@"path 后缀必须写“,@“path2"];
                    if (attachmentArr.count>0) {
                        [attachmentArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                            NSString *path=[[NSBundle mainBundle]pathForResource:obj ofType:nil];
                            NSURL *url=[NSURL fileURLWithPath:path];
                            [messageController addAttachmentURL:url withAlternateFilename:obj];
                        }];
                    }
                    
                    // 方法3
                    //            [messageController addAttachmentData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"photo.jpg" ofType:nil]]] typeIdentifier:@"public.image"  filename:@"photo.jpg"];
                }
                [self presentViewController:messageController animated:YES completion:nil];
            }

//
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    //
    switch (result) {
        case MessageComposeResultSent:
            NSLog(@"发送成功");
            break;
        case MessageComposeResultCancelled:
            NSLog(@"取消发送");
            break;
        default:
            NSLog(@"发送失败");
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
MFMailComposeViewController

#import 
            // 
            if ([MFMailComposeViewController canSendMail]) {
                //
                MFMailComposeViewController *mailController=[MFMailComposeViewController new];
                mailController.mailComposeDelegate=self;
                [mailController setToRecipients:@[@"收件人邮箱1",@"收件人邮箱2"]];
                if (@"抄送人".length>0) {
                    [mailController setCcRecipients:@[@"抄送人1",@"抄送人2"]];
                }
                if (@"密送人".length>0) {
                    [mailController setBccRecipients:@[@"密送人",@"密送人"]];
                }
                [mailController setSubject:@"主题"];
                [mailController setMessageBody:@"内容" isHTML:YES];
                if (@"附件".length>0) {
                    NSArray *attachments=@[@"附件1",@"附件2"];
                    [attachments enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                        NSString *file=[[NSBundle mainBundle] pathForResource:obj ofType:nil];
                        NSData *data=[NSData dataWithContentsOfFile:file];
                        [mailController addAttachmentData:data mimeType:@"image/jpeg" fileName:obj];
                    }];
                }
                [self presentViewController:mailController animated:YES completion:nil];
            }

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    switch (result) {
        case MFMailComposeResultSent:
            NSLog(@"发送成功");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"邮件已保存");
            break;
        case MFMailComposeResultCancelled:
            NSLog(@"取消发送");
            break;
        default:
            NSLog(@"发送失败");
            break;
    }
    if (error) {
        NSLog(@"发送邮件过程中发生错误,错误信息:%@",error.localizedDescription);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

你可能感兴趣的:(通讯录 与 发送邮件---iOS)