起因: 產品提個需求,調起短信頁面之后,要把短信內容傳輸過去,且點擊取消要返回短信列表頁面,而不是返回 APP。。。
下面來分步解決需求。需求可以分兩個部分:
1.講短信內容傳輸到短信頁面
2.取消或發送后留在短信頁面
1.短信內容傳輸到短信頁面
實現此功能,一般使用程序內調用系統。首先將頭文件引入
#import <MessageUI/MessageUI.h>
實現代碼:
if( [MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
controller.recipients = @[@"10086"];//發送短信的號碼,數組形式入參
controller.navigationBar.tintColor = [UIColor redColor];
controller.body = @"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];
}
如要獲取發送狀態,遵守代理 MFMessageComposeViewControllerDelegate
并實現代理方法
-(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;
}
}
此方法優點在于
1.發完短信或取消后能直接返回 APP
2.可將多個號碼傳輸到短信頁面
2.取消或發送后留在短信頁面
這個就很簡單啦,直接調用 openURL。發完短信或取消后將會到短信列表頁,不會直接返APP。但只能把一個號碼傳輸到短信頁面
NSString *phoneStr = [NSString stringWithFormat:@"10086"];//發短信的號碼
NSString *urlStr = [NSString stringWithFormat:@"sms://%@", phoneStr];
NSURL *url = [NSURL URLWithString:urlStr];
[[UIApplication sharedApplication] openURL:url];
至此,兩個需求都分別完成,但是并沒有達到產品的要求。經過分析得知,要停留在短信頁面,只能用采取第二種方法。所以,接下來需要解決的是怎么才能用第二種方法把短信內容傳過去。
觀察 openURL 傳入的參數 sms://手機號碼,這種格式于 url 有些相似,url 要拼接多個參數用 &,所以可以嘗試一下在號碼后拼接一個參數。在第一種方法中,短信內容賦值給 body,所以嘗試把入參拼成 sms://手機號碼&body=短信內容。就這樣完成需求。
NSString *phoneStr = [NSString stringWithFormat:@"10086"];//發短信的號碼
NSString *smsContentStr = [NSString stringWithFormat:@"短信內容"];
NSString *urlStr = [NSString stringWithFormat:@"sms://%@&body=%@", phoneStr, smsContentStr];
NSURL *url = [NSURL URLWithString:urlStr];
[[UIApplication sharedApplication] openURL:url];
關于拼參數的方法,并不是所有都是顯而易見的,也遇到過很多問題:例如是要 & 還是用 ? 來拼接;短信內容前是否需要帶參數名等等問題,經常很多次嘗試最終才得到的結果,深感不易。
2019.3.29 更新
之前一直沒注意傳輸中文, 會導致 URL 為 nil 的問題, 樓下有人提醒, 特此來修改
NSString *phoneStr = [NSString stringWithFormat:@"10086"];//發短信的號碼
NSString *smsContentStr = [NSString stringWithFormat:@"短信內容"];
NSString *urlStr = [NSString stringWithFormat:@"sms://%@&body=%@", phoneStr, smsContentStr];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; // 對中文進行編碼
NSURL *url = [NSURL URLWithString:urlStr];
if (@available(iOS 10.0, *)) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
} else {
[[UIApplication sharedApplication] openURL:url];
}