作者:Andy-清風。iOS 允許 App 透過自訂 URL Scheme 把某些動作交給系統內建應用處理,打電話、傳簡訊、發郵件都屬於這一類。做法統一是組出一個 URL,再交給 UIApplication 的 openURL: 執行。
+ (void)makeCall:(NSString *)phoneNumber {
if ([DeviceDetection isIPodTouch]) {
[UIUtils alert:kCallNotSupportOnIPod];
return;
}
NSString* numberAfterClear = [UIUtils cleanPhoneNumber:phoneNumber];
NSURL *phoneNumberURL = [NSURL URLWithString:
[NSString stringWithFormat:@"tel:%@", numberAfterClear]];
NSLog(@"make call, URL=%@", phoneNumberURL);
[[UIApplication sharedApplication] openURL:phoneNumberURL];
}
iPod Touch 沒有行動通訊模組,因此呼叫前先做能力檢測,避免跳出一個什麼都不會發生的空白狀態。cleanPhoneNumber 這一步則是把使用者輸入中的空白、括號、破折號等字元清掉,否則 tel: 後面夾帶非法字元會導致 openURL 失敗。
若希望撥號前先跳出確認對話框,可改用 telprompt: 這個 scheme,系統會先詢問使用者再進入電話應用。
+ (void)sendSms:(NSString *)phoneNumber {
if ([DeviceDetection isIPodTouch]) {
[UIUtils alert:kSmsNotSupportOnIPod];
return;
}
NSString* numberAfterClear = [UIUtils cleanPhoneNumber:phoneNumber];
NSURL *phoneNumberURL = [NSURL URLWithString:
[NSString stringWithFormat:@"sms:%@", numberAfterClear]];
NSLog(@"send sms, URL=%@", phoneNumberURL);
[[UIApplication sharedApplication] openURL:phoneNumberURL];
}
sms: scheme 會開啟「訊息」應用並帶入收件人,但不會自動送出,使用者仍需自行編輯內容並按下傳送。若要預先填入本文,iOS 4 之後支援 sms:number&body=內容 的寫法,但 body 參數需先做 URL 編碼。
最簡單的版本只帶收件人:
+ (void)sendEmail:(NSString *)phoneNumber {
NSURL *phoneNumberURL = [NSURL URLWithString:
[NSString stringWithFormat:@"mailto:%@", phoneNumber]];
NSLog(@"send email, URL=%@", phoneNumberURL);
[[UIApplication sharedApplication] openURL:phoneNumberURL];
}
需要帶副本收件人、主旨與本文時,把參數串進 query string,並務必做一次 URL 編碼:
+ (void)sendEmail:(NSString *)to
cc:(NSString*)cc
subject:(NSString*)subject
body:(NSString*)body {
NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@",
to, cc, subject, body];
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
中文一定要編碼。主旨或本文含中文、空白、& 等字元時,若不做 percent escape,整段 query 會被截斷或解析錯誤。stringByAddingPercentEscapesUsingEncoding: 在 iOS 9 之後已標記為廢棄,新專案請改用 stringByAddingPercentEncodingWithAllowedCharacters:。
openURL: 會回傳 BOOL。它代表「系統是否找到能處理這個 scheme 的應用」。建議檢查回傳值,例如模擬器上沒有電話應用,openURL 會回傳 NO,此時應給使用者一個提示而不是靜默失敗。判斷裝置能力也可用 [[UIApplication sharedApplication] canOpenURL:url] 先行詢問。
需要更完整的郵件體驗時,改用 MFMailComposeViewController。openURL 只能叫起系統郵件應用並離開你的 App;若希望使用者寄完信後自動回到 App、並能附加圖片或附件,就該用 MessageUI 框架內建的 compose 檢控器,記得實作 mailComposeController:didFinishWithResult:error: 以收回畫面,並在 iOS 4 之後加入 MessageUI.framework。