iOS了解之通訊錄與發(fā)送郵件

1. 通訊錄

  1. AddressBook框架

基于C語言,無法使用ARC來管理內(nèi)存,需要開發(fā)者自己管理內(nèi)存

ABAddressBookRef:代表通訊錄對象(有更改后必須保存)
ABRecordRef:一條記錄(聯(lián)系人 或 群組)通過ABRecordGetRecordType()獲取類型彬碱。通過ABRecordGetRecordID()獲取該記錄的唯一ID
ABPersonRef/ABGroupRef:聯(lián)系人/群組,一般不使用常柄,一般用:“kABPersonType”的ABRecordRef,“kABGroupType”的ABRecordRef


ABPersonCreate()        創(chuàng)建“kABPersonType”的ABRecordRef
ABRecordCopyValue()         獲取指定屬性值
ABRecordCopyCompositeName() 獲取記錄信息
ABRecordSetValue()  給紀(jì)錄設(shè)置單值屬性 搀擂。多值屬性:先創(chuàng)建一個ABMutableMultiValueRef類型的變量西潘,然后通過ABMultiValueAddValueAndLabel()方法依次添加屬性值,最后通過ABRecordSetValue()方法設(shè)置為記錄哨颂。
ABRecordRemoveValue()喷市。 刪除指定屬性值。
#import "YTPersonCCViewController.h"
#import <AddressBook/AddressBook.h>


@interface YTPersonCCViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong,nonatomic) NSMutableArray *personArr;     // 通訊錄聯(lián)系人
@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(@"未獲得通訊錄訪問授權(quán)");
            return ;
        }
        // 獲取 通訊錄聯(lián)系人
        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"];
    }
    
    // 獲取到 單條 聯(lián)系人記錄
    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){
    
    
        // 刪除聯(lián)系人(手機通訊錄中也刪掉了)
        ABRecordRef recordRef=(__bridge ABRecordRef)_personArr[indexPath.row];
        ABAddressBookRemoveRecord(_addressBook, recordRef, NULL);
        ABAddressBookSave(_addressBook, NULL);
        
        //
        [_personArr removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}









// 刪除一條記錄(根據(jù)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);
    
    
    // 添加到數(shù)據(jù)源威恼,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>

-》添加新聯(lián)系人頁面

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

-》查看 某聯(lián)系人詳情頁面(根據(jù)ID)

<ABPersonViewControllerDelegate>
    // 查看 某聯(lián)系人(根據(jù)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;
}

-》查看聯(lián)系人列表頁面

<ABPeoplePickerNavigationControllerDelegate>

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



-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    //
    NSLog(@"cancel select");
}
// 實現(xiàn)了本方法品姓,則下邊的屬性方法不再執(zhí)行
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person{

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

    //
    if(person&&property){
        NSLog(@"點擊了%i屬性:%@",property,(__bridge NSString*)ABRecordCopyValue(person, property));
    }
}

-》添加到未知聯(lián)系人

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. 發(fā)郵件

  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(@"發(fā)送成功");
            break;
        case MessageComposeResultCancelled:
            NSLog(@"取消發(fā)送");
            break;
        default:
            NSLog(@"發(fā)送失敗");
            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:@"內(nèi)容" 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(@"發(fā)送成功");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"郵件已保存");
            break;
        case MFMailComposeResultCancelled:
            NSLog(@"取消發(fā)送");
            break;
        default:
            NSLog(@"發(fā)送失敗");
            break;
    }
    if (error) {
        NSLog(@"發(fā)送郵件過程中發(fā)生錯誤,錯誤信息:%@",error.localizedDescription);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末箫措,一起剝皮案震驚了整個濱河市腹备,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌斤蔓,老刑警劉巖植酥,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異弦牡,居然都是意外死亡友驮,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門驾锰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來卸留,“玉大人,你說我怎么就攤上這事椭豫〕苌” “怎么了买喧?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長匆赃。 經(jīng)常有香客問我,道長今缚,這世上最難降的妖魔是什么算柳? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮姓言,結(jié)果婚禮上瞬项,老公的妹妹穿的比我還像新娘。我一直安慰自己何荚,他們只是感情好囱淋,可當(dāng)我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著餐塘,像睡著了一般妥衣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上戒傻,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天税手,我揣著相機與錄音,去河邊找鬼需纳。 笑死芦倒,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的不翩。 我是一名探鬼主播兵扬,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼口蝠!你這毒婦竟也來了器钟?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤亚皂,失蹤者是張志新(化名)和其女友劉穎俱箱,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體灭必,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡狞谱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了禁漓。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片跟衅。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖播歼,靈堂內(nèi)的尸體忽然破棺而出伶跷,到底是詐尸還是另有隱情掰读,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布叭莫,位于F島的核電站蹈集,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏雇初。R本人自食惡果不足惜拢肆,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望靖诗。 院中可真熱鬧郭怪,春花似錦、人聲如沸刊橘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽促绵。三九已至攒庵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間绞愚,已是汗流浹背叙甸。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留位衩,地道東北人裆蒸。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像糖驴,于是被迫代替她去往敵國和親僚祷。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容