首页 > 解决方案 > 在 Swift 4 中使用 Twilio 发送消息

问题描述

我正在尝试使用 Twilio API 发送消息,但它不起作用。我使用 Alamofire 发送消息。从 www.twilio.com 获取试用帐户并将相关的个人参数传递给我的程序。当我运行程序时,什么也没发生。出于安全原因,我使用假号码作为令牌、SID、电话号码等。

这是我的代码:

import UIKit
import Alamofire    

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()                
        if let accountSID = ProcessInfo.processInfo.environment["???????"], let authToken = ProcessInfo.processInfo.environment["?????"] {                
            let url = "https://api.twilio.com/2010-04-01/Accounts/\(accountSID)/Messages"
            let parameters = ["From": "+??????????", "To": "90????????", "Body": "Hello world"]

            Alamofire.request(url, method: .post, parameters: parameters)
                .authenticate(user: accountSID, password: authToken)
                .responseJSON { response in
                    debugPrint(response)                        
            }                                
            RunLoop.main.run()                
        }        
    }        
}

标签: swifttwilioalamofiremessage

解决方案


很可能您不应该使用authenticate这些参数,而是按照 Twillio 文档定义的方式直接将这些参数添加到您的请求中。authenticate仅用于 HTTP 身份验证并用于生成响应凭据,因此除非服务器提示进行身份验证,否则不会使用它。

此外,您不需要RunLoop.main.run(),iOS 应用程序自动运行循环。


推荐阅读