Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Validate and format a phone number with Twilio Lookup

See more Twilio Examples

Use Basic Lookup v2 to check a national-format number and obtain its E.164 and national display formats. Supply the two-letter country code for a national number. The example requests only the basic fields.

Read the boolean valid field even when the HTTP request succeeds. When it is false, display any validation_errors that Twilio supplies. Numbering-plan validation does not establish reachability or control of a phone. To confirm control, send an SMS verification code.

Twilio documentation

Chilkat Swift Downloads

Swift

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"

    //  The phone number is one URL path segment. Percent-encode spaces and any leading +.
    let number = CkoStringBuilder()!
    number.append(value: "020 7946 0018")
    var encoded: Bool = number.encode(encoding: "url_rfc3986", charset: "utf-8")
    if encoded != true {
        print("Could not encode the phone number.")
        return
    }

    let url = CkoStringBuilder()!
    url.append(value: "https://lookups.twilio.com/v2/PhoneNumbers/")
    url.append(value: number.getAsString())
    url.append(value: "?CountryCode=GB")
    let resp = CkoHttpResponse()!
    let reply = CkoJsonObject()!

    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: "valid").intValue != 5 {
        print("The lookup response is missing the validity flag.")
        return
    }

    if reply.bool(of: "valid") != true {
        print("The number is invalid for the specified country.")
        var i: Int = 0
        while (i < reply.size(ofArray: "validation_errors").intValue) {
            reply.i = i
            print("\(reply.string(of: "validation_errors[i]")!)")
            i = i + 1
        }

        return
    }

    if reply.jsonType(of: "phone_number").intValue != 1 {
        print("The lookup response is missing the E.164 number.")
        return
    }

    print("E.164: \(reply.string(of: "phone_number")!)")
    print("National format: \(reply.string(of: "national_format")!)")

}