iOS 发送短信有两种方法
方法一:
此方法有个缺点,iOS原生调用可以做短信多人发送,多账号之间用英文逗号","隔开
问题: 遇到js调用,即使是插件调用下面代码,只能识别第一个账号。逗号不被识别,导致多个账号不能被分开识别,打开短信息页面时只有一个长的号码
所以,推荐使用第二种方法
NSString* msg = [@"sms:13551,138450&body=This is content" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:msg];
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
}];
方法二
此方法依赖 MessageUI
框架使用,可以到短信息的单发、群发,是Apple官方推荐使用方法
代码如下:
//
// SmsModule.h
// Nick
//
// Created by Nick5683 on 2022/7/19.
// Copyright © 2020 Nick5683. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMessageComposeViewController.h>
@interface SmsModule : NSObject <MFMessageComposeViewControllerDelegate>
- (void)sendMessage:(NSString*)message recipients:(NSArray*)recipients;
@end
//
// SmsModule.m
// Nick
//
// Created by Nick5683 on 2022/7/19.
// Copyright © 2020 Nick5683. All rights reserved.
//
#import "SmsModule.h"
@implementation SmsModule
- (void)sendMessage:(NSString*)message recipients:(NSArray*)recipients;
if (![MFMessageComposeViewController canSendText]) {
dispatch_async(dispatch_get_main_queue(void), ^{
NSString *errorMessage = @"Sms Text not available.";
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]
message:errorMessage
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [
UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action){
}
];
[alert addAction:ok];
[currentViewController() presentViewController:alert animated:YES completion:nil];
});
return;
}
dispatch_async(dispatch_get_main_queue(void), ^{
MFMessageComposeViewController *composeViewController = [[MFMessageComposeViewController alloc] init];
composeViewController.messageComposeDelegate = self;
[composeViewController setBody:message];
if (recipients != nil) {
if ([recipients.firstObject isEqual: @""]) {
[recipients replaceObjectAtIndex:0 withObject:@"?"];
}
[composeViewController setRecipients:recipients];
}
// code to be executed on the main queue after delay
[self.viewController presentViewController:composeViewController animated:YES completion:nil];
});
}
#pragma mark - MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
NSString* message = @"";
switch(result) {
case MessageComposeResultCancelled:
message = @"Message cancelled.";
break;
case MessageComposeResultSent:
message = @"Message sent.";
break;
case MessageComposeResultFailed:
message = @"Message failed.";
break;
default:
message = @"Unknown error.";
break;
}
[self.viewController dismissViewControllerAnimated:YES completion:nil];
NSLog(@"----------%@",message);
}
@end