Swift Requires Chilkat v11.0.0+
Swift
Send an SMS with Twilio
See more Twilio Examples
Submit an SMS with the sender, recipient, and text as form fields. This example starts with Twilio test credentials and its successful test sender. Twilio simulates the submission without sending or billing for a message. Test credentials and test numbers.
For live SMS, use the live Account SID in the URL, authenticate with an API key SID and secret, and use an SMS-capable Twilio sender and a recipient in E.164 format. HTTP 201 creates the message. Save its SID to check delivery status later.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let http = CkoHttp()!
http.requireSslCertVerify = true
http.basicAuth = true
// Use the test Account SID and test Auth Token from the Twilio Console.
var accountSid: String? = "YOUR_TEST_ACCOUNT_SID"
http.login = accountSid
http.password = "YOUR_TEST_AUTH_TOKEN"
let url = CkoStringBuilder()!
url.append(value: "https://api.twilio.com/2010-04-01/Accounts/")
url.append(value: accountSid)
url.append(value: "/Messages.json")
// Add raw field values. Chilkat form-encodes them, including the + in a phone number.
let req = CkoHttpRequest()!
req.httpVerb = "POST"
req.contentType = "application/x-www-form-urlencoded"
req.addParam(name: "From", value: "+15005550006")
req.addParam(name: "To", value: "+12025550123")
req.addParam(name: "Body", value: "Hello from Twilio!")
let resp = CkoHttpResponse()!
let reply = CkoJsonObject()!
success = http.httpReq(url: url.getAsString(), request: req, response: resp)
if resp.statusCode.intValue == 0 {
print("\(http.lastErrorText!)")
return
}
var parsed: Bool = reply.load(json: resp.bodyStr)
if (success != true) || (resp.statusCode.intValue != 201) {
print("HTTP \(resp.statusCode.intValue)")
if (parsed == true) && (reply.hasMember(jsonPath: "code") == true) {
print("Twilio error \(reply.int(of: "code").intValue): \(reply.string(of: "message")!)")
}
return
}
if parsed != true {
print("Expected a JSON response.")
return
}
if (reply.jsonType(of: "sid").intValue != 1) || (reply.jsonType(of: "status").intValue != 1) {
print("The create response is missing the message SID or status.")
return
}
print("Message SID: \(reply.string(of: "sid")!)")
print("Initial status: \(reply.string(of: "status")!)")
}