【问题标题】:How do I send an SMS to multiple numbers via Twilio Functions?如何通过 Twilio Functions 向多个号码发送 SMS?
【发布时间】:2019-05-10 17:14:29
【问题描述】:

我有一个包含多个 UITextField 的页面,用户可以在其中输入多个联系号码。单击发送按钮时,它应向列出的联系人号码发送预设的文本消息。我正在使用 Twilio 来运行它,并且我正在使用函数功能,因此我不必创建单独的服务器。我遇到的问题是,当列出多个号码时,它不会发送消息。我该如何解决它,以便当用户输入多个号码时,它会将预设消息发送到这些号码?

我多次尝试修复它,但总是失败

这是我在 swift 中的代码:

    @IBOutlet weak var phonenumber: UITextField!
    @IBOutlet weak var phonenumber1: UITextField!
    @IBOutlet weak var phonenumber2: UITextField!
    @IBOutlet weak var phonenumber3: UITextField!

    var currentTextField: UITextField?

    private let contactPicker = CNContactPickerViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        configureTextFields()
        configureTapGesture()

     }


    private func configureTextFields() {
        phonenumber.delegate = self
        phonenumber1.delegate = self
        phonenumber2.delegate = self
        phonenumber3.delegate = self

    }

    private func configureTapGesture(){
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SelfTestTimer.handleTap))
        viewcontact.addGestureRecognizer(tapGesture)

    }

    @objc private func handleTap(){
        viewcontact.endEditing(true)

    }

    @IBAction func sendbutton(_ sender: Any) {

        presentAlert(alertTitle: "", alertMessage: "Make sure all the contacts have a country code attached to it ie +60", lastAction: UIAlertAction(title: "Continue", style: .default) { [weak self] _ in



        let headers = [
            "Content-Type": "//urlencoded"
        ]


        let parameters: Parameters = [
            "To": self?.currentTextField?.text ?? "", // if "To": is set to just one text field ie "To": self?.phonenumber1.text ?? "", the sms is sent

            "Body": "Tester",


        ]

        Alamofire.request("//path", method: .post, parameters: parameters, headers: headers).response { response in
            print(response)

        }
        }
    )}

}

extension SelfTestTimer: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        currentTextField = nil
        textField.resignFirstResponder()
        return true
    }


    func textFieldDidBeginEditing(_ textField: UITextField) {


        if textField.hasText{
            //dont do anything

        }else{
        currentTextField = textField
        contactPicker.delegate = self
        self.present(contactPicker, animated: true, completion: nil)
        }
        return
    }


}

这是我的 Twilio 函数中的代码:

exports.handler = function(context, event, callback) {
    const client = context.getTwilioClient();
    const to = event.To;
    const body = event.Body;
    client.messages.create({
      from: 'Twilio Phone Number',
      to: to,
      body: body,

    }).then(msg => {
      callback(null);
    });

};

我希望它能够向UITextFields 中列出的所有号码发送消息

【问题讨论】:

    标签: ios swift sms twilio twilio-functions


    【解决方案1】:

    这里是 Twilio 开发人员宣传员。 在sendButton 函数中,我将使用全局变量numArray 从文本框中创建一个电话号码数组:

    numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

    然后在同一个 sendButton 函数中,我将使用 urlSession 向您的 Twilio 函数 URL 发送 POST 请求。

    let Url = String(format: "REPLACE-WITH-YOUR-TWILIO-FUNCTION-URL")
            guard let serviceUrl = URL(string: Url) else { return }
            var request = URLRequest(url: serviceUrl)
            request.httpMethod = "POST"
            request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
            guard let httpBody = try? JSONSerialization.data(withJSONObject: numArray, options:[]) else {
                return
            }
            request.httpBody = httpBody
    
            let session = URLSession.shared
            session.dataTask(with: request) { (data, response, error) in
                if let response = response {
                    print(response)
                }
                if let data = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
                        print("json ", json)
                    } catch {
                        print(error)
                    }
                }
            }.resume()
    

    然后,您的 Twilio 函数应该包含这样的代码,以循环遍历电话号码数组并向每个号码发送消息:

    exports.handler = function(context, event, callback) {
        const client = context.getTwilioClient();
        var nums = [event[0], event[1], event[2], event[3]]; //hardcoded for 4 textboxes
        nums.forEach(function(arrayNum) {
            client.messages.create({
                to: arrayNum,
                from: "REPLACE-WITH-YOUR-TWILIO-NUMBER",
                body: "REPLACE WITH YOUR MESSAGE/WHATEVER MESSAGE YOU WANT!"
            }).then(msg => {
                callback(null, msg.sid);
            }).catch(err => callback(err));
        });
    };
    

    希望这会有所帮助!

    【讨论】:

    • 效果非常好。非常感谢:) @lizziepika
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2017-10-12
    相关资源
    最近更新 更多