首先,我真的很惊讶这不是重复的,因为在 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/