iOS開發中打電話發短信等功能的實現

在APP開發中,可能會涉及到打電話、發短信、發郵件等功能。好比說,一般一個產品的「關於」頁面,會有開發者的聯繫方式,理想狀況下,當用戶點擊該電話號碼時,可以自動的幫用戶撥出去,就涉及到了打電話的功能。java

iOS開發中,有三種方式能夠打電話:web

(1)直接跳到撥號界面,代碼以下app

NSURL *url = [NSURL URLWithString:@"tel://10010"];
 [[UIApplication sharedApplication] openURL:url];

缺點:電話打完後,不會自動回到原應用,直接停留在通話記錄頁面。框架

(2)撥號以前會彈框詢問,打完電話後能自動回到原應用。代碼以下:函數

NSURL *url = [NSURL URLWithString:@"telprompt://10010"];
[[UIApplication sharedApplication] openURL:url];

缺點:私有API,所以可能通不過蘋果官方審覈。若是是企業級應用(不須要上線appStore),能夠使用這個方法。測試

(3)建立一個UIWebView來加載URL,撥完後能自動回到原應用。代碼以下:url

UIWebView *webView = [[UIWebView alloc]init];
NSURL *url = [NSURL URLWithString:@"tel://10010"];
[webView loadRequest:[NSURLRequest requestWithURL:url ]];

推薦使用第三種方法。spa

有兩種方式能夠發短信。代理

(1)直接跳轉到發短信界面。代碼:code

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

缺點:不能定義發送短信的內容,且發完短信後不能自動回到原應用。

(2)使用MessageUI 框架發送短信,須要包含頭文件 #import <MessageUI/MessageUI.h>,代碼以下:

MFMessageComposeViewController *vc = [[MFMessageComposeViewController alloc]init];//設置短信內容vc.body = @"吃飯了沒";//設置收件人列表vc.recipients = @[@"10010",@"10086"];//設置代理vc.messageComposeDelegate = self;//顯示控制器[self presentViewController:vc animated:YES completion:nil];

另外實現代理函數:

/**
 *  點擊取消按鈕會自動調用
 *
 */- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

建議使用第二種方法。

有兩種方式能夠發郵件。

(1)用自帶的郵件客戶端,代碼以下:

NSURL *url = [NSURL URLWithString:@"mailto://10010@qq.com"];
[[UIApplication sharedApplication] openURL:url];

缺點:發完郵件後不會自動回到原應用

(2)相似於發短信的第二種方法,使用MessageUI,代碼以下:

if(![MFMailComposeViewController canSendMail]) return;
        MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];//設置郵件主題[vc setSubject:@"測試會議"];//設置郵件內容[vc setMessageBody:@"開會" isHTML:NO];//設置收件人列表[vc setToRecipients:@[@"test@qq.com"]];//設置抄送人列表[vc setCcRecipients:@[@"test1@qq.com"]];//設置代理vc.mailComposeDelegate = self;//顯示控制器[self presentViewController:vc animated:YES completion:nil];

實現代理方法:

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

推薦使用第二種方法。

相關文章
相關標籤/搜索