iOS - 邮件 短信 通讯录

本篇博客讲解了在iOS开发过程中如何使用系统邮件 短信 通讯录,解释不够全面的地方希望能及时的给与指正,博主会及时更新纠正.

1.邮件

1)引入MessageUI.framework框架
这里写图片描述

2)引头文件

#import <MessageUI/MessageUI.h>

3)签个协议

@interface SendEmailViewController ()<MFMailComposeViewControllerDelegate>

@end

4)ViewDidLoad方法(主要是加个button点击实现添加邮件功能)

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.backgroundColor = [UIColor cyanColor];
    button.frame = CGRectMake(120, 200, 100, 30);
    [button setTitle: @"邮件" forState: UIControlStateNormal];
    [button addTarget: self action: @selector(sendEMail) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview: button];
    // Do any additional setup after loading the view.
}

5)点击按钮触发添加邮件的方法

/** * 点击邮件按钮 */
-(void)sendEMail
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));

    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            /** * 发送邮件 */
            [self displayComposerSheet];
        }
        else
        {
            /** * 登录app */
            [self launchMailAppOnDevice];
        }
    }
    else
    {
        [self launchMailAppOnDevice];
    }
}

6)编辑邮件发送邮件

#pragma mark - 发送邮件
-(void)displayComposerSheet
{
    /** * 显示发邮件界面 */
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];

    mailPicker.mailComposeDelegate = self; 
    /** * 主题 */
    [mailPicker setSubject: @"EMail主题"];
    /** * 收件人 */
    NSArray *toRecipients = [NSArray arrayWithObject: @"[email protected]"];
    /** * 抄送 */
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"[email protected]", @"[email protected]", nil];
    [mailPicker setToRecipients: toRecipients];
    [mailPicker setCcRecipients: ccRecipients];

    /** * 添加附件(图片为例) */
    UIImage *addPic = [UIImage imageNamed: @"1.png"];
    NSData *imageData = UIImagePNGRepresentation(addPic);            // png或者jpg
    [mailPicker addAttachmentData: imageData mimeType: @"image/png" fileName: @"1.png"];

    /** * 添加正文 */
    NSString *emailBody = @"添加正文";
    [mailPicker setMessageBody:emailBody isHTML:YES];
    [self presentViewController:mailPicker animated:YES completion:^{

    }];
}

7)登录设备上的应用,使用其他应用发送邮件(例如:QQ邮箱)

#pragma mark - 登录设备上的应用
-(void)launchMailAppOnDevice
{
    NSString *recipients = @"mailto:[email protected]&subject=my email!";
    NSString *body = @"&body=email body!";

    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}

8)协议方法的实现

#pragma mark - 协议方法
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
/** * 发送成功或者失败后的处理(给予提示信息) */
{
    NSString *msg;

    switch (result)
    {
        case MFMailComposeResultCancelled:
            msg = @"邮件发送取消";
            [self alertWithTitle:nil msg:msg];
            break;
        case MFMailComposeResultSaved:
            msg = @"邮件保存成功";
            [self alertWithTitle:nil msg:msg];
            break;
        case MFMailComposeResultSent:
            msg = @"邮件发送成功";
            [self alertWithTitle:nil msg:msg];
            break;
        case MFMailComposeResultFailed:
            msg = @"邮件发送失败";
            [self alertWithTitle:nil msg:msg];
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:^{

    }];
}

9)提示方法(UIAlertView)

/** * 提示框 * *  @param title title(nil) *  @param msg 提示信息 */
- (void) alertWithTitle: (NSString *)title msg: (NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

10)运行结果:(效果图)
iOS - 邮件 短信 通讯录_第1张图片

2.短信

短信的发送有两种情况
第一种:进入系统短信发送,进入后不能退回到APP
第二种:进入短信添加界面,发完短信,回到当前APP

1.不能返回APP

1)导入框架MessageUI.framework
这里写图片描述
2)引入头文件

#import <MessageUI/MessageUI.h>

3)添加按钮,点击按钮触发点击事件(按钮添加不予以详述)

/** * 系统发送短信 * *  @param button nil */
- (void)buttonClicked:(UIButton *)button
{
    NSURL *url = [NSURL URLWithString:@"sms://10010"];
    [[UIApplication sharedApplication]openURL:url];

}

2.能够返回APP

1)添加框架,引入头文件(同上,这里不详述)
2)添加按钮,点击触发点击事件

/** * 发送后能回到APP * *  @param button nil */
- (void)button1Clicked:(UIButton *)button
{

    if ([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController *MFMC = [[MFMessageComposeViewController alloc]init];
        MFMC.messageComposeDelegate = self;
        MFMC.body = @"我爱你";
        MFMC.recipients = [NSArray arrayWithObject:@"10086"];

#pragma mark - 添加图片(可以发彩信)
        // /**
        // * 添加附件(图片为例)
        // */
        // UIImage *addPic = [UIImage imageNamed: @"1.png"];
        // NSData *imageData = UIImagePNGRepresentation(addPic); // png或者jpg
        // [MFMC addAttachmentData:imageData typeIdentifier:@"image/png" filename:@"1.png"];

        [self presentViewController:MFMC animated:YES completion:^{

        }];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备不支持短信功能" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
        [alert show];
    }  
}

3)协议方法的实现

#pragma mark - 协议方法
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    NSString *msg;
    switch (result) {
        case MessageComposeResultCancelled:

            msg = @"发送取消";
            [self alertWithTitle:nil msg:msg];
            break;
        case MessageComposeResultFailed:

            msg = @"发送取消";
            [self alertWithTitle:nil msg:msg];
            break;
        case MessageComposeResultSent:

            msg = @"发送成功";
            [self alertWithTitle:nil msg:msg];
            break;

        default:
            break;
    }

    [self dismissViewControllerAnimated:YES completion:^{

    }];
}

4)提示信息方法(方法同上)

/** * 提示框 * *  @param title title(nil) *  @param msg 提示信息 */
- (void) alertWithTitle: (NSString *)title msg: (NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];

}

5)运行结果(需要真机测试,模拟器不能够发送短信,以上代码经过真机测试,这里不提供结果效果图)

3.通讯录

获取手机上通讯录信息,重新展示通讯录(重点内容:获取通讯录内容)
1)框架的导入AddressBook.framework,引入头文件

这里写图片描述

/* AddressBook.framework是c api直接访问操作 通讯录数据库框架 * * AddressBookUI.framework是oc 界面交互框架 */
#import <AddressBook/AddressBook.h>

2)需要的属性和协议

@interface AddressBookViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *addressBook;
@property (nonatomic, retain) UITableView *addressBookTableView;

@end

3)ViewDidLoad方法(没有进行封装,代码冗长,谅解…)

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    /** * 添加一个返回按钮 用于返回 */
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, 30, 100, 20);
    button.backgroundColor = [UIColor cyanColor];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

    /** * 初始化 */
    self.addressBook = [NSMutableArray array];

    /** * 新建一个通讯录,获取本地通讯录数据库 */
    ABAddressBookRef address = nil;


    address = ABAddressBookCreateWithOptions(nil, nil);

    /** * 获取通讯录权限 * *  @param 0 * *  @return */

    /* 在GCD中有三个函数是semaphore的操作,分别是:   dispatch_semaphore_create   创建一个semaphore   dispatch_semaphore_signal   发送一个信号   dispatch_semaphore_wait    等待信号 */
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    ABAddressBookRequestAccessWithCompletion(address, ^(bool granted, CFErrorRef error) {
        dispatch_semaphore_signal(sema);
    });

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    //address = ABAddressBookCreate();/* 该方法适用6.0版本之前, 可以加个版本判断 */
    //__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_6_0

    /** * 获取通讯录中的所有人 * *  @param address 通讯录 * *  @return 结构体数组allPeople */
    CFArrayRef allPeople  = ABAddressBookCopyArrayOfAllPeople(address);

    /** * 获取通讯录中联系人的个数 * *  @param address 通讯录address * *  @return CFIndex */
    CFIndex numPeople = ABAddressBookGetPersonCount(address);

    for (NSInteger i = 0; i < numPeople; i++) {

        /** 定义一个联系人的Model */
        PeopleModel *peo = [[PeopleModel alloc]init];
        /** * 获取通讯录中的一个人 * *  @param allPeople 联系人数组 *  @param i 下标 * *  @return 单个人 */
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

        /** * 获取一个人的名字 * *  @param person 通讯录中的联系人 *  @param kABPersonFirstNameProperty * *  @return 获取一个人的名字 */
        CFTypeRef name = ABRecordCopyValue(person, kABPersonFirstNameProperty);
        /** * 获取的名字要进行类型转换 * *  @param NSString Core Foundation 对象 * *  @return Objective-C 对象name */
        NSString *nameString = (__bridge NSString *)name;


        /* 获取电话号码 方法同上 */
        ABMultiValueRef telePhone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSString *telePhoneString = (__bridge NSString *)ABMultiValueCopyValueAtIndex(telePhone, 0);

        peo.tel = telePhoneString;
        peo.name = nameString;

        /** * 获取唯一标识 * *  @param int 转换为整型 * *  @return recordID */
        peo.recordID = (int)ABRecordGetRecordID(person);

        [self.addressBook addObject:peo];

#pragma mark - 获取通讯录信息(其他的详细介绍)
        /* kABPersonLastNameProperty; // 姓氏 kABPersonMiddleNameProperty; // 中间名 kABPersonPrefixProperty; // 前缀 kABPersonSuffixProperty; // 后缀 kABPersonNicknameProperty; // 昵称 kABPersonFirstNamePhoneticProperty; // 名字的汉语拼音或者音标 kABPersonLastNamePhoneticProperty; // 姓氏汉语拼音或者音标 kABPersonMiddleNamePhoneticProperty; // 中间名的汉语拼音或者音标 kABPersonOrganizationProperty; // 组织名 kABPersonJobTitleProperty; // 工作头衔 kABPersonDepartmentProperty; // 部门 kABPersonNoteProperty; // 备注 kABPersonBirthdayProperty; // 生日 kABPersonCreationDateProperty; // 创建时间 kABPersonModificationDateProperty; // 修改日期 kABPersonPhoneProperty ; //电话号码属性 kABMultiStringPropertyType;//类型 kABPersonEmailProperty ; //e-mail属性 kABMultiStringPropertyType;//类型 kABPersonURLProperty ; //URL属性 kABMultiStringPropertyType;//类型 kABPersonRelatedNamesProperty; // 亲属关系人属性 kABMultiStringPropertyType;//类型 kABPersonAddressProperty ; //地址属性 kABMultiDictionaryPropertyType;//类型 kABPersonInstantMessageProperty;//及时聊天属性 kABMultiDictionaryPropertyType;//类型 kABPersonSocialProfileProperty; //社交账号属性 kABMultiDictionaryPropertyTypel;//类 */ 

    }

    /* 重铺通讯录 */
    [self tableViewSubview];
}

4)重铺通讯录tableView

- (void)tableViewSubview
{
    self.addressBookTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 50) style:UITableViewStylePlain];
    self.addressBookTableView.dataSource = self;
    self.addressBookTableView.delegate = self;
    [self.view addSubview:self.addressBookTableView];


}
#pragma mark - tableView协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.addressBook count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"reuse"];
    }

    PeopleModel *person = [self.addressBook objectAtIndex:indexPath.row];

    cell.textLabel.text = person.name;
    cell.detailTextLabel.text = person.tel;

    return cell;
}

5)联系人Model

@interface PeopleModel : NSObject

@property (nonatomic, assign) NSInteger recordID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *tel;

@end

6)运行结果(效果图)获取系统通讯录(如果是中文名字:firstname lastname都要获取,拼接字符串显示姓名)

你可能感兴趣的:(ios,邮件,通讯录,短信,界面)