【问题标题】:Twilio Send SMS in swiftTwilio 快速发送短信
【发布时间】:2016-08-01 21:27:32
【问题描述】:

我正在尝试制作一个应用程序,当您按下按钮时,它会向预设号码发送短信,并且我正在使用 Twilio 发送短信。问题是我在我的应用程序中使用 Swift,他们目前没有 swift 示例。这是我发送消息的代码:

func sendSMS()
{

    let twilioSID = "AC11ed62fdb971a8f56d9be531a5ce40c2"
    let twilioSecret = "mySecretID"

    let fromNumber = "number"
    let toNumber = "number"
    let message = "This is a test message"


    // Build the request
    let request = NSMutableURLRequest(URL: NSURL(string:"https://\(twilioSID):\(twilioSecret)@api.twilio.com/2010-04-01/Accounts/\(twilioSID)/SMS/Messages")!)
    request.HTTPMethod = "POST"
    request.HTTPBody = "From=\(fromNumber)&To=\(toNumber)&Body=\(message)".dataUsingEncoding(NSUTF8StringEncoding)

    // Build the completion block and send the request
    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
        print("Finished")
        if let data = data, responseDetails = NSString(data: data, encoding: NSUTF8StringEncoding) {
            // Success
            print("Response: \(responseDetails)")
        } else {
            // Failure
            print("Error: \(error)")
        }
    }).resume()
}

但是每当我尝试运行该功能时,我都会得到这个

Finished
Response: <?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse><RestException><Code>20003</Code><Detail>Your AccountSid or AuthToken was incorrect.</Detail><Message>Authentication Error - No credentials provided</Message><MoreInfo>https://www.twilio.com/docs/errors/20003</MoreInfo><Status>401</Status></RestException></TwilioResponse>

我知道我的凭据是正确的.....

有没有更好的方法来做到这一点?有人有例子吗?

【问题讨论】:

  • iOS 不允许您在 URL 中嵌入用户名/密码,因为它不安全。您需要在请求中添加身份验证标头。
  • @Paulw11 我该怎么做呢? Swift 是新的,所以网上教程不多

标签: ios swift xcode swift2 twilio


【解决方案1】:

Matthew,如上面的 cmets 所述/出于安全原因,我们不建议您通过客户端代码从 REST API 发送 SMS。

我们建议您使用此处示例中的可用帮助程序库之一将您的凭据和 SMS 发送打包在后端应用程序中: https://www.twilio.com/docs/api/rest/sending-messages

实际上,我的一位同事 wrote a post 为 Android 社​​区解决了这个问题,看起来我们绝对应该为 Swift 做同样的事情,这将是我的速度。

[更新]How to send an SMS from Swift post.

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2015-08-08
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多