iOS了解之通讯录与发送邮件

1. 通讯录

  1. 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 <AddressBook/AddressBook.h>


@interface YTPersonCCViewController ()<UITableViewDelegate,UITableViewDataSource>
@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<phoneCount;i++){
    
        //
        NSString *phoneName=(__bridge NSString*)ABMultiValueCopyLabelAtIndex(phoneRef, i);
        NSString *phoneNumber=(__bridge NSString*)ABMultiValueCopyLabelAtIndex(phoneRef, i);
        NSLog(@"%@,%@",phoneName,phoneNumber);
    }
    // 头像
    if(ABPersonHasImageData(recordRef)){
        NSData *imgData=(__bridge NSData*)ABPersonCopyImageData(recordRef);
        cell.imageView.image=[UIImage imageWithData:imgData];
    }else{
        cell.imageView.image=nil;
    }
    cell.tag=ABRecordGetRecordID(recordRef);        // 用于修改
    cell.textLabel.text=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
    cell.detailTextLabel.text=(__bridge NSString*)ABMultiValueCopyValueAtIndex(phoneRef, 0);
    
    return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    if(editingStyle==UITableViewCellEditingStyleDelete){
    
    
        // 删除联系人(手机通讯录中也删掉了)
        ABRecordRef recordRef=(__bridge ABRecordRef)_personArr[indexPath.row];
        ABAddressBookRemoveRecord(_addressBook, recordRef, NULL);
        ABAddressBookSave(_addressBook, NULL);
        
        //
        [_personArr removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}









// 删除一条记录(根据name)
-(void)removePersonWithName:(NSString *)name{
    
    //
    CFStringRef personNameRef=(__bridge CFStringRef)name;
    
    // 可能有多条
    CFArrayRef recordArrRef=ABAddressBookCopyPeopleWithName(_addressBook, personNameRef);
    CFIndex count=CFArrayGetCount(recordArrRef);
    for(CFIndex i=0;i<count;i++){
    
        //
        ABRecordRef recordRef=CFArrayGetValueAtIndex(recordArrRef, i);
        ABAddressBookRemoveRecord(_addressBook, recordRef, NULL);
    }
    ABAddressBookSave(_addressBook, NULL);
    
    //
    CFRelease(recordArrRef);
}


// 新增一条记录
-(void)addPerson{

    // 新增一条记录
    ABRecordRef recordRef=ABPersonCreate();
    // name
    ABRecordSetValue(recordRef, kABPersonFirstNameProperty, (__bridge CFTypeRef)@"少林张三丰", NULL);
    ABRecordSetValue(recordRef, kABPersonLastNameProperty, (__bridge CFTypeRef)@"110", NULL);
    //
    ABMutableMultiValueRef muRef=ABMultiValueCreateMutable(kABStringPropertyType);
    ABMultiValueAddValueAndLabel(muRef, (__bridge CFStringRef)@"130****5423", kABWorkLabel, NULL);
    ABRecordSetValue(recordRef, kABPersonPhoneProperty, muRef, NULL);
    
    ABAddressBookAddRecord(_addressBook, recordRef, NULL);
    ABAddressBookSave(_addressBook, NULL);
    
    //
    CFRelease(recordRef);
    CFRelease(muRef);
    
    
    // 添加到数据源,reloadData
}

// 更新一条记录
-(void)updatePerson{

    //
    ABRecordRef recordRef=ABAddressBookGetPersonWithRecordID(_addressBook, 110);    // 保存在cell.tag中
    // name
    ABRecordSetValue(recordRef, kABPersonFirstNameProperty, (__bridge CFTypeRef)@"少林张三丰", NULL);
    ABRecordSetValue(recordRef, kABPersonLastNameProperty, (__bridge CFTypeRef)@"110", NULL);
    //
    ABMutableMultiValueRef muRef=ABMultiValueCreateMutable(kABStringPropertyType);
    ABMultiValueAddValueAndLabel(muRef, (__bridge CFStringRef)@"130****5423", kABWorkLabel, NULL);
    ABRecordSetValue(recordRef, kABPersonPhoneProperty, muRef, NULL);
    
    ABAddressBookAddRecord(_addressBook, recordRef, NULL);
    ABAddressBookSave(_addressBook, NULL);
    
    //
    CFRelease(muRef);
}







-(void)dealloc{

    if(_addressBook!=NULL){
        //
        CFRelease(_addressBook);
    }
}
@end

  1. AddressBookUI框架
#import <AddressBookUI/AddressBookUI.h>
<ABNewPersonViewControllerDelegate,ABUnknownPersonViewControllerDelegate,ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate,UINavigationControllerDelegate>

-》添加新联系人页面

<ABNewPersonViewControllerDelegate>
    //
    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)

<ABPersonViewControllerDelegate>
    // 查看 某联系人(根据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;
}

-》查看联系人列表页面

<ABPeoplePickerNavigationControllerDelegate>

    //
    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;
}

2. 发邮件

  1. MFMessageComposeViewController
#import <MessageUI/MessageUI.h>
<MFMessageComposeViewControllerDelegate>
            //
            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];
}
  1. MFMailComposeViewController
<MFMailComposeViewControllerDelegate>
#import <MessageUI/MessageUI.h>
            // 
            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];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容