Swift Requires Chilkat v11.0.0+
Swift
Download the media files from a Twilio MMS
See more Twilio Examples
Supply the Message SID of a received or sent MMS. List its media records, then request each media resource without the .json extension to download the file bytes. Twilio may return a temporary HTTPS download URL. The example uses a separate HTTP client for that URL so the Twilio API key stays with the API host.
Run in an empty output directory. Files are written as mms-media-1.bin, mms-media-2.bin, and so on. The code prints the media SID and MIME type alongside each filename. An empty media list produces a count of zero.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Load an API key for the Twilio account from private application configuration.
let http = CkoHttp()!
http.requireSslCertVerify = true
http.basicAuth = true
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: "YOUR_ACCOUNT_SID")
url.append(value: "/Messages")
url.append(value: "/")
url.append(value: "YOUR_MESSAGE_SID")
url.append(value: "/Media")
let mediaBase = CkoStringBuilder()!
mediaBase.appendSb(sb: url)
url.append(value: ".json")
// Handle the API redirect explicitly so a signed download uses no Twilio credentials.
http.followRedirects = false
let download = CkoHttp()!
download.requireSslCertVerify = true
let fileResp = CkoHttpResponse()!
let fileUrl = CkoStringBuilder()!
let filename = CkoStringBuilder()!
let mediaSid = CkoStringBuilder()!
var saved: Int = 0
let resp = CkoHttpResponse()!
let reply = CkoJsonObject()!
var more: Bool = true
while (more == true) {
success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
if resp.statusCode.intValue == 0 {
print("No HTTP response from Twilio.")
return
}
var parsed: Bool = reply.load(json: resp.bodyStr)
if (success != true) || (resp.statusCode.intValue != 200) {
print("Twilio returned HTTP \(resp.statusCode.intValue)")
if (parsed == true) && (reply.jsonType(of: "code").intValue == 2) {
print("Twilio error: \(reply.int(of: "code").intValue) \(reply.string(of: "message")!)")
}
return
}
if parsed != true {
print("Expected a JSON response from Twilio.")
return
}
if reply.jsonType(of: "media_list").intValue != 4 {
print("Expected an array of media items.")
return
}
var count: Int = reply.size(ofArray: "media_list").intValue
var i: Int = 0
while (i < count) {
reply.i = i
mediaSid.setString(value: reply.string(of: "media_list[i].sid"))
if mediaSid.length.intValue == 0 {
print("Media item is missing its SID.")
return
}
fileUrl.setString(value: mediaBase.getAsString())
fileUrl.append(value: "/")
fileUrl.appendSb(sb: mediaSid)
success = http.httpNoBody(verb: "GET", url: fileUrl.getAsString(), response: fileResp)
if (fileResp.statusCode.intValue >= 300) && (fileResp.statusCode.intValue < 400) {
fileUrl.setString(value: fileResp.getHeaderField(fieldName: "Location"))
if fileUrl.starts(with: "https://", caseSensitive: false) != true {
print("Expected an HTTPS media download URL.")
return
}
success = download.httpNoBody(verb: "GET", url: fileUrl.getAsString(), response: fileResp)
}
if (success != true) || (fileResp.statusCode.intValue != 200) {
print("Media download failed for \(mediaSid.getAsString()!). HTTP \(fileResp.statusCode.intValue)")
return
}
filename.setString(value: "mms-media-")
filename.appendInt(value: saved + 1)
filename.append(value: ".bin")
success = fileResp.saveBodyBinary(path: filename.getAsString())
if success == false {
print("\(fileResp.lastErrorText!)")
return
}
print("\(filename.getAsString()!) \(mediaSid.getAsString()!) \(reply.string(of: "media_list[i].content_type")!)")
saved = saved + 1
i = i + 1
}
if reply.isNull(of: "next_page_uri") == true {
more = false
}
else {
url.setString(value: reply.string(of: "next_page_uri"))
if url.starts(with: "/2010-04-01/Accounts/", caseSensitive: true) != true {
print("Expected a Twilio relative next-page URI.")
return
}
url.prepend(value: "https://api.twilio.com")
}
}
print("Media files saved: \(saved)")
}