iOS发送短信功能的实现代码

2020-01-21 00:41:18刘景俊

检测是否可以发送短信,还是需要有一个触发事件的,代码如下:


- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
  
  UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(140, 100, 100, 100)];
  button.backgroundColor = [UIColor blackColor];
  [button setTitle:@"发送短信" forState:UIControlStateNormal];
  [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  [button addTarget:self action:@selector(showSMSPicker:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:button];
  
  UILabel * feedbackMsg = [[UILabel alloc]initWithFrame:CGRectMake(10, 300, self.view.frame.size.width -20, 30)];
  feedbackMsg.textAlignment = NSTextAlignmentCenter;
  [self.view addSubview:feedbackMsg];
  self.feedbackMsg = feedbackMsg;
}

嗯,到了实现协议方法的时候了:


// -------------------------------------------------------------------------------
// messageComposeViewController:didFinishWithResult:
// Dismisses the message composition interface when users tap Cancel or Send.
// Proceeds to update the feedback message field with the result of the
// operation.
// 当用户点击取消或发送时,关闭消息组合界面。
// 收到更新反馈消息字段的结果操作。
// -------------------------------------------------------------------------------
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller 
       didFinishWithResult:(MessageComposeResult)result
{
  self.feedbackMsg.hidden = NO;
  // Notifies users about errors associated with the interface
  // 通知用户与界面相关的错误
  switch (result)
  {
    case MessageComposeResultCancelled: //取消
      self.feedbackMsg.text = @"Result: SMS sending canceled";
      break;
    case MessageComposeResultSent: //发送
      self.feedbackMsg.text = @"Result: SMS sent";
      break;
    case MessageComposeResultFailed: //失败
      self.feedbackMsg.text = @"Result: SMS sending failed";
      break;
    default: //默认
      self.feedbackMsg.text = @"Result: SMS not sent";
      break;
  }
  
  [self dismissViewControllerAnimated:YES completion:NULL];
}

Demo运行结果如下:

iOS发送短信,iOS,实现发短信功能

iOS发送短信,iOS,实现发短信功能

iOS发送短信,iOS,实现发短信功能

至此,我们的发送短信功能就实现了,是不是很简单!但是,当年也是怂过啊,所以,特写此文,以纪念当年怂过的日子。