在 iOS 中呼叫系統簡訊功能,大致可分為兩種情境:一種是直接跳出系統簡訊 App,另一種是在 App 內開啟簡訊撰寫介面。第二種做法的好處是使用者寄出簡訊後,通常可以回到原本的 App,操作流程較順暢。
這種方式很簡單,直接使用 openURL 開啟 sms:// 即可。
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://13888888888"]];
若希望在 App 內完成簡訊撰寫,需要導入 MessageUI 框架,並使用 MFMessageComposeViewController。
使用者完成或取消操作後,會觸發代理方法,可在此處理成功、失敗與取消三種結果。
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
[self dismissViewControllerAnimated:YES completion:nil];
if (result == MessageComposeResultSent) {
NSLog(@"簡訊已送出");
} else if (result == MessageComposeResultCancelled) {
NSLog(@"使用者取消簡訊");
} else {
NSLog(@"簡訊送出失敗");
}
}實務上建議先呼叫 canSendText 檢查裝置是否支援簡訊功能,避免在不支援的環境中直接開啟簡訊介面。