發送郵件
1.匯入庫檔案:MessageUI.framework
2.引入標頭檔
3.實現代理<MFMailComposeViewControllerDelegate> 和 <UINavigationControllerDelegate>
程式碼範例:
複製代碼 代碼如下:
- (void)didClickSendEmailButtonAction{
if ([MFMailComposeViewController canSendMail] == YES) {
MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
// 設定代理(與以往代理不同,不是"delegate",千萬不能忘記呀,代理有3步)
mailVC.mailComposeDelegate = self;
// 收件者
NSArray *sendToPerson = @[@"humingtao2014@gmail.com"];
[mailVC setToRecipients:sendToPerson];
// 抄送
NSArray *copyToPerson = @[@"humingtao2013@126.com"];
[mailVC setCcRecipients:copyToPerson];
// 密送
NSArray *secretToPerson = @[@"563821250@qq.com"];
[mailVC setBccRecipients:secretToPerson];
// 主題
[mailVC setSubject:@"hello world"];
[self presentViewController:mailVC animated:YES completion:nil];
[mailVC setMessageBody:@"魑魅魍魎,哈哈呵呵嘿嘿霍霍" isHTML:NO];
}else{
NSLog(@"此裝置不支援郵件發送");
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
switch (result) {
case MFMailComposeResultCancelled:
NSLog(@"取消發送");
break;
case MFMailComposeResultFailed:
NSLog(@"發送失敗");
break;
case MFMailComposeResultSaved:
NSLog(@"儲存草稿檔案");
break;
case MFMailComposeResultSent:
NSLog(@"發送成功");
break;
default:
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
// 系統發送,模擬器不支援,要用真機測試
- (void)didClickSendSystemEmailButtonAction{
NSURL *url = [NSURL URLWithString:@"humingtao2014@gmail.com"];
if ([[UIApplication sharedApplication] canOpenURL:url] == YES) {
[[UIApplication sharedApplication] openURL:url];
}else{
NSLog(@"此裝置不支援");
}
}
傳送簡訊
前面三步引入配置和郵件發送一樣
複製代碼 代碼如下:
// 調用系統API傳送簡訊
- (void)didClickSendMessageButtonAction{
if ([MFMessageComposeViewController canSendText] == YES) {
MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
// 設定代理<MFMessageComposeViewControllerDelegate>
messageVC.messageComposeDelegate = self;
// 發送To Who
messageVC.recipients = @[@"18757289870"];
messageVC.body = @"hello world";
[self presentViewController:messageVC animated:YES completion:nil];
}else{
NSLog(@"此裝置不支援");
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
switch (result) {
case MessageComposeResultCancelled:
NSLog(@"取消發送");
break;
case MessageComposeResultFailed:
NSLog(@"發送失敗");
break;
case MessageComposeResultSent:
NSLog(@"發送成功");
break;
default:
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
// 調用系統應用程式發送訊息
- (void)didClickSendMessage2ButtonAction{
NSURL *url = [NSURL URLWithString:@"sms:18656348970"];
if ([[UIApplication sharedApplication] canOpenURL:url] == YES) {
[[UIApplication sharedApplication] openURL:url];
}else{
NSLog(@"失敗");
}
}