最近在做关于发送短信功能,发现苹果自带一款iMessage可以通过走网络来发送短信,但前提是两个苹果设备都要激活iMessage功能。
下面分享一下项目中添加发送短信功能:
1.首先要在TARGETS->Build Phases->Link Binary With Libraries中添加一个类库MessageUI.framework
2.导入头文件:
#import
3.编写代码:
- (void)showMessageView {
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
controller.recipients = [NSArray arrayWithObject:@"18888888888"];
controller.body = @"who is 保安";
controller.messageComposeDelegate = self;
[self presentViewController:controller animated:YES completion:nil];
} else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"该设备不支持短信功能" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAlertAction = [UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"是的");
}];
UIAlertAction *cancelAlertAction = [UIAlertAction actionWithTitle:@"没错" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"没错");
}];
[alertController addAction:okAlertAction];
[alertController addAction:cancelAlertAction];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"评价一下他吧";
textField.delegate = self;
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"临终遗言";
textField.delegate = self;
}];
[self presentViewController:alertController animated:YES completion:nil];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
[controller dismissViewControllerAnimated:NO completion:nil];
switch (result) {
case MessageComposeResultCancelled: { // 取消发送
}
break;
case MessageComposeResultFailed: { // 发送失败
NSLog(@"失败 ");
}
break;
case MessageComposeResultSent: { // 发送成功
NSLog(@"成功 ");
}
break;
default:
break;
}
}