swift UI专项训练40 用swift实现打电话和发短信功能

前端之家收集整理的这篇文章主要介绍了swift UI专项训练40 用swift实现打电话和发短信功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天来讲一下如何让我们的APP可以访问系统的短信和电话功能。首先来说短信功能,比较简单,跟之前的做法差别不大,要使用UIApplication,它是一个单例。我们的功能是点击一个按钮,然后拨通一个内置的电话,需要在button的action中加入如下语句:

  1. @IBAction func phoneBtn(sender:UIButton){
  2. // var url1 = NSURL(string: "tel://"+canguanArray[0].tel)
  3. var url1 = NSURL(string: "tel://10086")
  4. UIApplication.sharedApplication().openURL(url1!)
  5. }

tel关键字代表电话,跟之前oc上的做法差不多,如果要拨打的电话是传值获得的,参考注释中的写法。除了tel关键字,还有sms关键字:
  1. var url1 = NSURL(string: "sms://10086")

这样的话是打开了10086的短信界面,如果我们要打开一个浏览器界面,使用下面代码
  1. var url1 = NSURL(string: "http://blog.csdn.net/cg1991130")

不过使用这种方法发短信不能设置短信的内容,只能设置收信人。如果我们想要自定义发短信的内容的话,使用下面的方法

首先在vc中导入头文件

  1. import MessageUI

之后让vc继承MFMessageCompose的代理:
  1. class CaipinDetailViewController: UIViewController,MFMessageComposeViewControllerDelegate
  1. func canSendText() -> Bool{
  2. return MFMessageComposeViewController.canSendText()
  3. }//用来指示一条消息能否从用户处发送
  4. func configuredMessageComposeViewController() -> MFMessageComposeViewController{
  5. let messageComposeVC = MFMessageComposeViewController()
  6. messageComposeVC.messageComposeDelegate = self
  7. messageComposeVC.body = "HI! \(caipinArray[0].rest) 的 \(caipinArray[0].name) 味道很不错,邀你共享 -来自SoFun的邀请"
  8. return messageComposeVC
  9. }
  10. func messageComposeViewController(controller: MFMessageComposeViewController!,didFinishWithResult result: MessageComposeResult) {
  11. controller.dismissViewControllerAnimated(true,completion: nil)
  12. }

然后在按钮的action方法中加入以下代码
  1. @IBAction func share(sender: UIButton) {
  2. let shareView = ShareViewController()
  3. self.presentViewController(shareView,animated: true,completion: nil)
  4. }
  5. @IBAction func message(sender: UIButton) {
  6. if self.canSendText(){
  7. let messageVC = self.configuredMessageComposeViewController()
  8. presentViewController(messageVC,completion: nil)
  9. } else {
  10. let errorAlert = UIAlertView(title: "不能发送",message: "你的设备没有短信功能",delegate: self,cancelButtonTitle: "取消")
  11. }
  12.  
  13. }

我们在真机上测试一下,效果图:


猜你在找的Swift相关文章