您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 兩種簡訊呼叫方式:跳系統 App 與 App 內建編輯器

編輯:iOS 7 技巧

App 裡常有「把這筆訂單資訊用簡訊傳給朋友」這類需求。iOS 提供兩條路,取決於你要不要留在自己的 App 裡。

方式一:直接喚起系統簡訊 App

最省事的做法,用 openURL: 丟一個 sms:// 連結即可:

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

缺點很明顯:使用者被踢到簡訊 App,傳完之後不會自動回到你的 App,流程中斷。

方式二:在 App 內以 Modal 呈現編輯器

這個做法的好處是發送後使用者還留在 App 內,體驗完整得多。先匯入框架與標頭:

#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:@[@"15888888888", @"12399999999"]
                  title:@"test"
                   body:@"這是測試用短信,勿回復!"];

務必保留 canSendText 的檢查:iPad 或沒有 SIM 卡的裝置回傳 NO,若不判斷就硬推 modal,畫面會一片空白。另外,recipients 是陣列,因此群組傳送直接塞多筆號碼即可。若你的目標已經是 iOS 7 以後的環境,UIAlertView 建議換成 UIAlertController,前者在 iOS 9 起已正式被取代。

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