标签:
ios中发送短信有两种
1.程序外调用系统短信
2.程序内调用系统发短信
第一种比较简单,直接调用url就可以了
oc下的代码为
1 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"sms:%@",@"13888888888"]]]
swift下的代码
UIApplication.sharedApplication().openURL(NSURL(string: "sms:13888888888")!)
第二种
oc下的代码
#import
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result { [self dismissViewControllerAnimated:YES completion:nil]; switch (result) { case MessageComposeResultSent: //信息传送成功 break; case MessageComposeResultFailed: //信息传送失败 break; case MessageComposeResultCancelled: //信息被用户取消传送 break; default: break; } }
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body { if( [MFMessageComposeViewController canSendText] ) { MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init]; controller.recipients = phones; controller.navigationBar.tintColor = [UIColor redColor]; controller.body = body; controller.messageComposeDelegate = self; [self presentViewController:controller animated:YES completion:nil]; [[[[controller viewControllers] lastObject] navigationItem] setTitle:title];//修改短信界面标题 } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@提示信息 message:@该设备不支持短信功能 delegate:nil cancelButtonTitle:@确定 otherButtonTitles:nil, nil]; [alert show]; } }
参数phones:发短信的手机号码的数组,数组中是一个即单发,多个即群发。
[self showMessageView:[NSArray arrayWithObjects:@13888888888,@13999999999, nil] title:@test body:@你是土豪么,么么哒];
Swift版本
import MessageUI
之后让vc继承MFMessageCompose的代理:
class CaipinDetailViewController: UIViewController,MFMessageComposeViewControllerDelegate func canSendText() -> Bool{ return MFMessageComposeViewController.canSendText() }//用来指示一条消息能否从用户处发送 func configuredMessageComposeViewController() -> MFMessageComposeViewController{ let messageComposeVC = MFMessageComposeViewController() messageComposeVC.messageComposeDelegate = self messageComposeVC.body = "HI! \(caipinArray[0].rest) 的 \(caipinArray[0].name) 味道很不错,邀你共享 -来自SoFun的邀请" return messageComposeVC } func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { controller.dismissViewControllerAnimated(true, completion: nil) }
然后在按钮的action方法中加入以下代码:
@IBAction func share(sender: UIButton) { let shareView = ShareViewController() self.presentViewController(shareView, animated: true, completion: nil) } @IBAction func message(sender: UIButton) { if self.canSendText(){ let messageVC = self.configuredMessageComposeViewController() presentViewController(messageVC, animated: true, completion: nil) } else { let errorAlert = UIAlertView(title: "不能发送", message: "你的设备没有短信功能", delegate: self, cancelButtonTitle: "取消") } }
我们在真机上测试一下,效果图:
标签:
原文地址:http://www.cnblogs.com/silenter/p/5687189.html