Swift Requires Chilkat v11.0.0+
Swift
List Twilio message history
See more Twilio Examples
List inbound and outbound messages, newest sent date first. Print the Message SID, direction, and status so you can distinguish incoming messages from outbound submissions and see their latest state.
Each response contains a messages array and a next_page_uri. Follow that URI until it is null. PageSize limits one response. Use credentials for the account whose history you want to read.
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
// Load the owning Account SID and an API key from application configuration.
var accountSid: String? = "YOUR_ACCOUNT_SID"
http.login = "YOUR_API_KEY_SID"
http.password = "YOUR_API_KEY_SECRET"
let url = CkoStringBuilder()!
url.append(value: "https://api.twilio.com/2010-04-01/Accounts/")
url.append(value: accountSid)
url.append(value: "/Messages.json")
url.append(value: "?PageSize=50")
let resp = CkoHttpResponse()!
let reply = CkoJsonObject()!
var total: Int = 0
var more: Bool = true
while (more == true) {
success = http.httpNoBody(verb: "GET", url: url.getAsString(), 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 != 200) {
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: "messages").intValue != 4 {
print("Expected a messages array.")
return
}
var count: Int = reply.size(ofArray: "messages").intValue
var i: Int = 0
while (i < count) {
reply.i = i
print("\(reply.string(of: "messages[i].sid")!) \(reply.string(of: "messages[i].direction")!) \(reply.string(of: "messages[i].status")!)")
i = i + 1
}
total = total + count
// Twilio supplies a relative URI with the cursor and returns null on the last page.
if reply.isNull(of: "next_page_uri") == true {
more = false
}
else {
if reply.jsonType(of: "next_page_uri").intValue != 1 {
print("Expected a next-page URI or null.")
return
}
url.setString(value: "https://api.twilio.com")
url.append(value: reply.string(of: "next_page_uri"))
}
}
print("Messages found: \(total)")
}