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

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

@IBAction func phoneBtn(sender:UIButton){// var url1 = NSURL(string: "tel://"+canguanArray[0].tel)var url1 = NSURL(string: "tel://10086")UIApplication.sharedApplication().openURL(url1!)}tel关键字代表电话,,跟之前oc上的做法差不多,如果要拨打的电话是传值获得的,参考注释中的写法。除了tel关键字,还有sms关键字:

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

var url1 = NSURL(string: "")不过使用这种方法发短信不能设置短信的内容,只能设置收信人。如果我们想要自定义发短信的内容的话,使用下面的方法:

首先在vc中导入头文件:

import MessageUI之后让vc继承MFMessageCompose的代理:

class CaipinDetailViewController: UIViewController,MFMessageComposeViewControllerDelegate func canSendText() -> Bool{return MFMessageComposeViewController.canSendText()}//用来指示一条消息能否从用户处发送func configuredMessageComposeViewController() -> MFMessageComposeViewController{let messageComposeVC = MFMessageComposeViewController()messageComposeVC.messageComposeDelegate = selfmessageComposeVC.body = "HI! \(caipinArray[0].rest) 的 \(caipinArray[0].name) 味道很不错,邀你共享 -来自SoFun的邀请"return messageComposeVC}func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {controller.dismissViewControllerAnimated(true, completion: nil)}然后在按钮的action方法中加入以下代码:

@IBAction func share(sender: UIButton) {let shareView = ShareViewController()self.presentViewController(shareView, animated: true, completion: nil)}@IBAction func message(sender: UIButton) {if self.canSendText(){let messageVC = self.configuredMessageComposeViewController()presentViewController(messageVC, animated: true, completion: nil)} else {let errorAlert = UIAlertView(title: "不能发送", message: "你的设备没有短信功能", delegate: self, cancelButtonTitle: "取消")}}我们在真机上测试一下,效果图:

去看日出,去散步,去欣赏大自然,

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

相关文章:

你感兴趣的文章:

标签云: