2

I'm trying to make an app that when you press a button it sends a text message to a preset number, and I am using Twilio for the SMS messages. The issue is that I am using Swift for my app, and they have no examples in swift currently. This is my code for sending the message:

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()
}

But whenever I try and run that function, I get this

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>

I know that my credentials are correct.....

Is there a better way of doing this? Does anyone have an example out there?

Matthew Bergwall
  • 310
  • 1
  • 10
  • 2
    iOS won't let you embed usernames/passwords in the URL as it isn't secure. You will need to add an authentication header to your request. – Paulw11 Aug 01 '16 at 21:33
  • @Paulw11 How would I go about doing that? Swift is new so there are not many tutorials online – Matthew Bergwall Aug 02 '16 at 00:52

1 Answers1

1

Matthew, as mentioned in the comments above/we do not recommend that you send SMS from the REST API via client side code for security reasons.

We suggest that you wrap your credentials and sending of the SMS in a backend app using one of the available helper libraries in the examples seen here: https://www.twilio.com/docs/api/rest/sending-messages

A colleague of mine actually wrote a post to address this for the Android community and it looks like we should definitely do the same for Swift, which would be more my speed.

[Update]: How to send an SMS from Swift post.

Hope this helps.

Megan Speir
  • 3,745
  • 1
  • 15
  • 25