问题描述
首先,我真的很惊讶这不是重复的,因为在Objective-C中有大量的堆栈溢出问题可以解决此问题,但是我还没有看到使用Swift的好答案.
First of all, I'm really surprised that this is not a duplicate, because there are TONS of stackoverflow questions that solve this in Objective-C, but I have yet to see a good answer that used Swift.
我正在寻找的是Swift中的代码段,该代码段将任意字符串作为文本消息的正文发送到给定的电话号码.从本质上讲,我想要苹果公司的此官方文档,但使用Swift而不是Objective-C.
What I'm looking for is a code snippet in Swift that sends an arbitrary string as a the body of a text message to given phone number. Essentially, I'd like something like this from Apple's official documentation, but in Swift instead of Objective-C.
我想这并不太困难,因为它可以在Android中只需几行代码即可完成.
I imagine this isn't too difficult, as it can be done in just a couple of lines of code in Android.
我要寻找的是5-20行Swift代码,我不同意它的范围太广.在Java(适用于Android)中,解决方案如下所示:
What I'm looking for is 5-20 lines of Swift code, I do not agree that this is too broad. In Java (for Android), the solution looks like this:
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的用法,上面的内容尚不清楚.
Now this is the android solution, and it's only 11 lines. Java tends to be much more verbose than Swift, so I doubt what I'm asking is "too broad", it is more likely that I don't know how to use the Objective-C MessageComposer object, because the documentation that I linked to above is unclear with regard to usage in Swift.
推荐答案
不确定您是否真的找到了答案.我也遇到了类似的情况,遇到了这种解决方案,并使它起作用.
Not sure if you really got the answer. I was in a similar hunt and came across this solution and got it to work.
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
}
}
这篇关于使用Swift在iOS中发送短信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!