ios - 在 iOS 中使用 Swift 发送短信

标签 ios swift iphone sms imessage

首先,我真的很惊讶这不是重复的,因为在 Objective-C 中有大量的 stackoverflow 问题解决了这个问题,但我还没有看到使用 Swift 的好的答案。

我正在寻找的是 Swift 中的一个代码片段,它将任意字符串作为文本消息的正文发送到给定的电话号码。本质上,我想要类似 this 的东西来自 Apple 的官方文档,但使用的是 Swift 而不是 Objective-C。

我想这并不太难,因为在 Android 中只需几行代码即可完成。

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

package com.company.appname;
import android.app.Activity;
import android.telephony.SmsManager;
public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        public static final mPhoneNumber = "1111111111";
        public static final mMessage = "hello phone";
        SmsManager.getDefault().sendTextMessage(mPhoneNumber, null, mMessage, null, null);
     }
}

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

最佳答案

不确定您是否真的得到了答案。我进行了类似的搜索,发现了这个解决方案并让它发挥作用。

import UIKit
import MessageUI

class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {

    @IBOutlet weak var phoneNumber: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func sendText(sender: UIButton) {
        if (MFMessageComposeViewController.canSendText()) {
            let controller = MFMessageComposeViewController()
            controller.body = "Message Body"
            controller.recipients = [phoneNumber.text]
            controller.messageComposeDelegate = self
            self.presentViewController(controller, animated: true, completion: nil)
        }
    }

    func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
        //... handle sms screen actions
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewWillDisappear(animated: Bool) {
        self.navigationController?.navigationBarHidden = false
    }
}

关于ios - 在 iOS 中使用 Swift 发送短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26350220/

相关文章:

ios - 创建类的实例返回警告?

ios - 为什么我的 UISwipeGestureRecognizer 出现这个错误?

ios - 从另一个自定义应用程序打开自定义企业应用程序时遇到问题

ios - 需要帮助理解 View Controller 生命周期

ios - 在像 Twitter 这样的 UIImageView 中缩放图像

iphone - 如何在设备上更改 iOS 应用程序的文件名?

ios - 获取按钮操作 : UICollectionView Cell

swift - Firebase 将快照值转换为对象

iPhone - 设置 UIImage 位置

iphone - 在 iOS 中提取 MP3 专辑插图