使用Swift在iOS中发送短信

前端之家收集整理的这篇文章主要介绍了使用Swift在iOS中发送短信前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
首先,我真的很惊讶,这并不重要,因为在Objective-C中有解决这个问题的stackoverflow问题的TONS,但是我还没有看到使用Swift的好的答案。

我正在寻找的是Swift中的一个代码片段,它将任意字符串作为文本消息的正文发送给给定的电话号码。从本质上讲,我想从Apple官方文档中获得像this这样的东西,但是在Swift而不是Objective-C。

我想象这并不是太困难,因为它可以在Android中的几行代码中完成。

编辑:我正在寻找的是5-20行的Swift代码,我不同意这太广泛了。在Java(对于Android)中,解决方案如下所示:

  1. package com.company.appname;
  2. import android.app.Activity;
  3. import android.telephony.SmsManager;
  4. public class MainActivity extends Activity {
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. public static final mPhoneNumber = "1111111111";
  8. public static final mMessage = "hello phone";
  9. SmsManager.getDefault().sendTextMessage(mPhoneNumber,null,mMessage,null);
  10. }
  11. }

现在这是android的解决方案,只有11行。 Java往往比Swift更为冗长,所以我怀疑我所要求的是“太广泛”了,更不可能我不知道如何使用Objective-C MessageComposer对象,因为我链接的文档以上对于Swift中的使用情况尚不清楚。

不知道你是否真的得到答案。我正在进行类似的狩猎,并遇到这个解决方案,并让它上班。
  1. import UIKit
  2. import MessageUI
  3.  
  4. class ViewController: UIViewController,MFMessageComposeViewControllerDelegate {
  5.  
  6. @IBOutlet weak var phoneNumber: UITextField!
  7.  
  8. override func viewDidLoad() {
  9. super.viewDidLoad()
  10. }
  11.  
  12. @IBAction func sendText(sender: UIButton) {
  13. if (MFMessageComposeViewController.canSendText()) {
  14. let controller = MFMessageComposeViewController()
  15. controller.body = "Message Body"
  16. controller.recipients = [phoneNumber.text]
  17. controller.messageComposeDelegate = self
  18. self.presentViewController(controller,animated: true,completion: nil)
  19. }
  20. }
  21.  
  22. func messageComposeViewController(controller: MFMessageComposeViewController!,didFinishWithResult result: MessageComposeResult) {
  23. //... handle sms screen actions
  24. self.dismissViewControllerAnimated(true,completion: nil)
  25. }
  26.  
  27. override func viewWillDisappear(animated: Bool) {
  28. self.navigationController?.navigationBarHidden = false
  29. }
  30. }

猜你在找的Swift相关文章