To send a text from Swift, run the call on your server, never in the iOS app. The server makes an HTTPS POST to /v1/messages with URLSession, keeps the API key in an environment variable and sends the recipient and message as JSON. The app only asks your server to send, after your own login check.

We make Ready, so the example uses the Ready REST API and only the request shape we document. The patterns carry over to any provider: a Codable request, an Idempotency-Key per message and retry rules that never text anyone twice. The code assumes Swift 5.9 or later and works the same in a Vapor route or any other server-side Swift process.

Why the key stays out of the app

An API key in a shipped app isn't secret. Anyone can download the app, pull the binary apart and read strings out of it. Hiding the key in an obfuscated constant, a plist or a build setting only slows that down. Anyone who can proxy the app's traffic reads the header off the wire.

A leaked key can send texts that you pay for, from your numbers, to anyone. It can also burn your sender reputation, which carriers judge by the traffic, and a reputation hit lands on every customer you text for. You can't recall an installed binary, so rotating the key means every old app version breaks.

So the shape is fixed:

  1. The app calls your own backend, signed in as the user.
  2. Your backend decides whether this user may text this person, and what the message says.
  3. Your backend calls Ready with the key.

The same rule covers Swift code running in a notification extension or a widget. If it ships to a device, it can't hold the key.

What you need before the first request

  • An API key. Ready authenticates with an X-API-Key header. Load it from the environment on the server.
  • A card and a number. A card on file and a number of your own are required to send, and the number is $2 a month. To build first, create a test key (Settings, Developers, Environment: Test). It simulates every send with no card, number or charge.
  • Consent. Each request carries consent_attested: true, your promise that the recipient agreed to texts. Only set it when it's true.
  • A plan for registration. An account can send up to 500 texts a calendar month until its business is verified and registration is paid for. Most approvals take 1 to 14 days. Our 10DLC explainer for SaaS platforms covers why carriers ask.

Every text is charged from the first one: each segment costs $0.0075 plus a $0.0045 carrier fee. Screening, the optional scrub and validation checks, is extra when you switch it on.

Send a text with async/await

The endpoint is POST https://api.tryready.com/v1/messages. The body takes to in E.164 format (a 10-digit US number is treated as +1), body and consent_attested.

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

struct SendRequest: Encodable {
    let to: String
    let body: String
    let consentAttested: Bool
}

struct SendResult {
    let status: Int
    let data: Data
}

enum ReadyClient {
    static let baseURL = URL(string: "https://api.tryready.com")!

    static func send(to: String, body: String, idempotencyKey: String) async throws -> SendResult {
        guard let apiKey = ProcessInfo.processInfo.environment["READY_API_KEY"] else {
            fatalError("READY_API_KEY is not set")
        }

        let encoder = JSONEncoder()
        encoder.keyEncodingStrategy = .convertToSnakeCase

        var request = URLRequest(url: baseURL.appendingPathComponent("v1/messages"))
        request.httpMethod = "POST"
        request.timeoutInterval = 30
        request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key")
        request.httpBody = try encoder.encode(
            SendRequest(to: to, body: body, consentAttested: true)
        )

        let (data, response) = try await URLSession.shared.data(for: request)
        let status = (response as? HTTPURLResponse)?.statusCode ?? 0
        return SendResult(status: status, data: data)
    }
}

A few choices in there matter. Codable builds the payload, so a name with a quote or a newline can't produce broken JSON. The snake-case strategy turns consentAttested into consent_attested, so your Swift stays idiomatic. And timeoutInterval gives a stalled call a deadline, so a slow network doesn't hang a task forever.

The call prints no response fields on purpose. For exact response fields and error bodies, use the messages API reference rather than a blog post's summary.

Two optional fields are worth knowing. from picks one of your own numbers, and media_url sends a picture as MMS. Leave from out and Ready picks the number: the one this contact already texts with, otherwise your primary number.

Calling it from a Vapor route

In Vapor, wrap the client in a route that checks who's asking first.

app.post("notify", ":orderID") { req async throws -> HTTPStatus in
    let user = try req.auth.require(User.self)
    let order = try await Order.find(req.parameters.get("orderID"), on: req.db)
        .unwrap(or: Abort(.notFound))
    guard order.$user.id == user.id else { throw Abort(.forbidden) }

    let result = try await ReadyClient.send(
        to: order.phone,
        body: "Your order #\(order.number) has shipped.",
        idempotencyKey: "order-\(order.id!)-shipped"
    )
    return (200..<300).contains(result.status) ? .accepted : .badGateway
}

The authorization check is the point. The app never names the number or the text. Your server pulls both from its own records, so a stolen session can't turn your route into a free text sender.

Retry rules that don't double-send

Networks fail. If a request times out, you don't know whether the text went out, and retrying blindly can text a customer twice. Generate one UUID per message, or derive a stable one from the event as above, store it with the record and send the same key on every attempt. Our post on deterministic idempotency keys for SMS covers the derivation.

What came backWhat to do
URLError.timedOut or a dropped connectionRetry with the same key
409 idempotency_in_progressWait a few seconds, retry with the same key
2xxDone. Store the result
5xxDon't retry yet. Check GET /v1/messages, then send again with a new key if it never went out
Other 4xxDon't retry. The same request fails the same way

A 5xx is stored under the key and replayed, so the same key returns the same error and sends nothing. If you checked and the text didn't go out, that resend is a new send and needs a new key.

func sendWithRetry(to: String, body: String, key: String) async throws -> SendResult {
    var delay: UInt64 = 500_000_000
    for attempt in 1...4 {
        do {
            let result = try await ReadyClient.send(to: to, body: body, idempotencyKey: key)
            let inProgress = result.status == 409
                && String(decoding: result.data, as: UTF8.self).contains("idempotency_in_progress")
            if !inProgress || attempt == 4 { return result }
        } catch let error as URLError where error.code == .timedOut || error.code == .networkConnectionLost {
            if attempt == 4 { throw error }
        }
        try await Task.sleep(nanoseconds: delay)
        delay *= 2
    }
    fatalError("unreachable")
}

Notice that the key is a parameter, not created inside the loop. A fresh UUID per attempt defeats the purpose. When retries run out, keep the record pending with its key and try again later instead of marking it failed. Our post on retries and failure handling goes deeper.

Sending to many numbers

For the same message to many recipients, POST /v1/messages/bulk takes to as an array, with at most 100 recipients per call. Split a longer list into chunks, and give each chunk its own stored key so a crash and restart reuses the key instead of resending. In Swift, a TaskGroup with a small fixed width fits well. Carriers cap segments per second per registered campaign, so more tasks don't mean faster delivery. See the bulk messages docs.

A worked cost example

Assume a Vapor service sends 2,000 single-segment shipping updates in a month, with screening off. That's 2,000 segments, and the text bill is 2,000 × ($0.0075 + $0.0045), plus $2 for the number. Plain characters keep a message at one segment, since one emoji drops the limit from 160 characters to 70.

Ready's all-in prices per segment include the carrier fee but not screening: Scrub lists and Number validation, the two switches in Settings under Compliance, each add $0.003 per segment when switched on, shown as screening on your bill, and both are off by default. Unless you turn the opt-out footer off, the first text to each contact, and one again from time to time, also gets "Reply STOP to opt out" and your business name if the message does not already have them, so a text close to the segment limit can bill one more segment.

Accounts opened before 17:55 UTC on November 12, 2026 keep their signup prices, shown under Billing, and so do the sub-accounts they open.

Frequently asked questions

Can I send SMS directly from an iOS app?

Not safely. Anything inside the app, including the API key, can be extracted by someone who downloads it. Have the app call your server, and let the server hold the key and make the request.

Do I need a Swift SDK to send SMS?

No. URLSession and Codable are enough. The API is one JSON POST to /v1/messages with an X-API-Key header, so the client above replaces a library.

Should I retry a 500 response?

Not with the same key. A 5xx is stored and replayed, so the same key returns the same error. Check GET /v1/messages to see whether the text went out, then send again with a new key only if it didn't.

How many recipients can one bulk call take?

At most 100 per call. Split a longer list into chunks with their own idempotency keys.

Where to go next

Sending is half the story. A delivery report or a reply reaches your server by webhook, so add one route that verifies the signature and answers fast. The API quickstart walks through a key, a first send and a webhook.