您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 呼叫系統簡訊的兩種做法:跳出去 vs. 留在 App 內

編輯:iOS 開發綜合

應用裡要發簡訊,蘋果給了兩條路,體驗差別不小,選哪條取決於你是否希望使用者留在 App 裡。

一、跳出 App 發簡訊

最省事的方式,直接 openURL:

 NSURL *url = [NSURL URLWithString:@"sms://15888888888"]; [[UIApplication sharedApplication]openURL:url];

缺點也很明顯:使用者被帶去「訊息」App,發完得自己切回來。

二、在 App 內彈出簡訊介面

这种做法的好處是發完能無縫回到應用,適合發送驗證碼邀請、意見回饋這類場景。

先引入 MessageUI.framework 與頭檔:

 #import <MessageUI/MessageUI.h>

然後遵循 MFMessageComposeViewControllerDelegate 並實作回調:

 #pragma mark - 代理方法 -(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; } }

發送方法本體:

 #pragma mark - 發送短信方法 -(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]; } }

呼叫起來很直觀:

 [self showMessageView:[NSArray arrayWithObjects:@"15888888888",@"12399999999", nil] title:@"test" body:@"這是測試用短信,勿回復!"];

實務上有一點務必注意:調用前一定要先判斷 [MFMessageComposeViewController canSendText]。iPad 模擬器或某些無行動網路的裝置並不具備簡訊能力,不做判斷直接 present 會崩潰。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved