首先,我真的很惊讶,这并不重要,因为在Objective-C中有解决这个问题的stackoverflow问题的TONS,但是我还没有看到使用Swift的好的答案。
我正在寻找的是Swift中的一个代码片段,它将任意字符串作为文本消息的正文发送给给定的电话号码。从本质上讲,我想从Apple官方文档中获得像this这样的东西,但是在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);
- }
- }
现在这是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
- }
- }