【发布时间】: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