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

iOS 開發實戰:用 openURL 打通電話、簡訊、郵件與瀏覽器

編輯:iOS 開發綜合

在 iOS 中要跳出自己的 App 去撥號、寫信或開網頁,最輕量的做法就是利用 UIApplication 的 openURL:,把一組自訂 scheme 的 URL 交給系統,由系統決定該喚起哪個內建應用。下面把常用的幾種情境整理成一份可直接複製的清單。

一、喚起郵件客戶端

使用 mailto:// 前綴即可開啟預設的郵件撰寫畫面:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://admin@hzlzh.com"]];

二、撥打電話

最直覺的寫法是用 tel:// 或 tel: 搭配號碼:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://8008808888"]];

這種方式會直接切換到電話 App,使用者按結束通話後畫面會停留在通話紀錄,不會自動回到你的 App。若希望通話結束後能回到原本的操作流程,可以改用 UIWebView 來觸發撥號:

UIWebView *callWebview = [[UIWebView alloc] init];
NSURL *telURL = [NSURL URLWithString:@"tel:10086"];  // tel:// 與 tel: 皆可
[callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
[self.view addSubview:callWebview];  // 記得加入檢視階層

另外還有一種私有 scheme telprompt://,撥完會自動跳回 App,但屬於非公開 API,提交審核有風險:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://10086"]];

三、開啟簡訊

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://800888"]];

四、開啟 Safari

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.hzlzh.com"]];

五、想預先帶入簡訊內容?改用 MessageUI

sms:// 只能指定收件者號碼,無法預填本文。若需要同時帶入內容與多位收件人,就得改用 MessageUI 框架:

  1. 專案加入 MessageUI.framework
  2. 引入標頭:#import <MessageUI/MFMessageComposeViewController.h>
  3. 讓控制器實作 MFMessageComposeViewControllerDelegate

核心程式碼如下:

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller =
        [[[MFMessageComposeViewController alloc] init] autorelease];
    if ([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent");
    else
        NSLog(@"Message failed");
}

小提醒:簡訊編輯畫面預設顯示英文,若要在 .xib 中補上一組 Chinese 的 Localization,介面就會跟著系統語言走。

實務上還要注意:模擬器無法真正撥號,且 canSendText 在缺少 SIM 卡或裝置不支援時會回傳 NO,記得先判斷再呼叫,避免流程中斷。

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