陈斌彬的技术博客

Stay foolish,stay hungry

iOS调用发短信功能

iOS中可以使用两种方式发送短信,最简单是使用openURL:

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms://10010"]];//发短信

上面方式无法指定短信内容,iOS4.0新加入了MFMessageComposeViewController和MFMessageComposeViewControllerDelegate,提供了发送短信的接口,可以像发送邮件那样不用跳出程序来发送短信. 介绍可参阅Message UIFramework Reference

MFMessageComposeViewController提供了操作界面使用前必须检查canSendText方法,若返回NO则不应将这个controller展现出来,而应该提示用户不支持发送短信功能.

messageComposeDelegate :代理,处理发送结果
recipients  :收信人<列表,支持群发>
body :短信内容

Frameworks中要引入MessageUI.framework

#import <MessageUI/MessageUI.h>
添加协议:<MFMessageComposeViewControllerDelegate>
#import <MessageUI/MessageUI.h>

@interface DemoViewController : UIViewController <MFMessageComposeViewControllerDelegate>

@end

调用MFMessageComposeViewController,同时实现协议MFMessageComposeViewControllerDelegate。

- (void)showMessageView
{

    if( [MFMessageComposeViewController canSendText] ){

        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc]init]; //autorelease];

        controller.recipients = [NSArray arrayWithObject:@"10010"];     
        controller.body = @"测试发短信";        
        controller.messageComposeDelegate = self;

        [self presentModalViewController:controller animated:YES];

        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"测试短信"];//修改短信界面标题
    }else{

        [self alertWithTitle:@"提示信息" msg:@"设备没有短信功能"];        
    }    
}


//MFMessageComposeViewControllerDelegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{

    [controller dismissModalViewControllerAnimated:NO];//关键的一句   不能为YES

    switch ( result ) {

        case MessageComposeResultCancelled:

            [self alertWithTitle:@"提示信息" msg:@"发送取消"]; 
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"提示信息" msg:@"发送成功"]; 
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"提示信息" msg:@"发送失败"]; 
            break;
        default:
            break; 
    }
}


- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg {


    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
           message:msg
           delegate:self
           cancelButtonTitle:nil
           otherButtonTitles:@"确定", nil];

   [alert show];

}

Resource Reference