Swift Requires Chilkat v11.0.0+
Swift
Look up an IP address with the ip-api free endpoint
See more Geolocation Examples
This example uses the free, keyless ip-api endpoint for non-commercial use. The free service supports HTTP and is limited to 45 requests per minute per source IP. Its Pro service provides HTTPS and commercial use. ip-api Pro.
Always include status and message when selecting fields. Invalid or private addresses can produce status=fail inside a JSON response. Retain the X-Rl and X-Ttl response values between calls, and pause further requests when X-Rl reaches zero.
IP geolocation estimates a network location. VPNs, mobile gateways, and anycast routing can affect the result. City and coordinate fields can be missing or approximate. The sample address 8.8.8.8 is a public DNS address used to demonstrate the request.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Use a public IP address. Provider results can change as their databases are updated.
var ipAddress: String? = "8.8.8.8"
let http = CkoHttp()!
http.requireSslCertVerify = true
http.connectTimeout = 10
http.readTimeout = 30
http.accept = "application/json"
// The free endpoint is HTTP-only. This single lookup sends no API credentials.
let url = CkoStringBuilder()!
url.append(value: "http://ip-api.com/json/")
url.append(value: http.urlEncode(str: ipAddress))
let parameters = CkoJsonObject()!
parameters.updateString(jsonPath: "fields", value: "status,message,query,country,countryCode,regionName,city,lat,lon,timezone")
let response = CkoHttpResponse()!
success = http.httpParams(verb: "GET", url: url.getAsString(), json: parameters, response: response)
if response.statusCode.intValue == 0 {
// Request diagnostics can contain an API key. Report transport failure without logging credentials.
print("No HTTP response. Check connectivity, DNS, and TLS configuration.")
return
}
// Save these values if the application will make further requests.
var remaining: String? = response.getHeaderField(fieldName: "X-Rl")
if remaining == "0" {
print("Rate limit reached. Wait \(response.getHeaderField(fieldName: "X-Ttl")!) seconds before the next request.")
}
let json = CkoJsonObject()!
var parsed: Bool = json.load(json: response.bodyStr)
if (success != true) || (response.statusCode.intValue < 200) || (response.statusCode.intValue >= 300) {
print("Lookup failed. HTTP \(response.statusCode.intValue)")
if parsed == true {
if json.jsonType(of: "message").intValue == 1 {
print("\(json.string(of: "message")!)")
}
}
return
}
if parsed != true {
print("Expected a JSON object in the lookup response.")
return
}
if json.string(ofEquals: "status", value: "success", caseSensitive: true) != true {
print("The service could not complete the lookup.")
if json.jsonType(of: "message").intValue == 1 {
print("\(json.string(of: "message")!)")
}
return
}
if (json.jsonType(of: "query").intValue != 1) || (json.string(ofEquals: "query", value: "", caseSensitive: true) == true) {
print("The response did not contain the expected IP address.")
return
}
print("IP address: \(json.string(of: "query")!)")
if (json.jsonType(of: "country").intValue == 1) && (json.string(ofEquals: "country", value: "", caseSensitive: true) != true) {
print("Country: \(json.string(of: "country")!)")
}
else {
print("Country: unavailable")
}
if (json.jsonType(of: "countryCode").intValue == 1) && (json.string(ofEquals: "countryCode", value: "", caseSensitive: true) != true) {
print("Country code: \(json.string(of: "countryCode")!)")
}
else {
print("Country code: unavailable")
}
if (json.jsonType(of: "regionName").intValue == 1) && (json.string(ofEquals: "regionName", value: "", caseSensitive: true) != true) {
print("Region: \(json.string(of: "regionName")!)")
}
else {
print("Region: unavailable")
}
if (json.jsonType(of: "city").intValue == 1) && (json.string(ofEquals: "city", value: "", caseSensitive: true) != true) {
print("City: \(json.string(of: "city")!)")
}
else {
print("City: unavailable")
}
if (json.jsonType(of: "timezone").intValue == 1) && (json.string(ofEquals: "timezone", value: "", caseSensitive: true) != true) {
print("Time zone: \(json.string(of: "timezone")!)")
}
else {
print("Time zone: unavailable")
}
// Missing coordinates stay unavailable. A numeric zero is a valid coordinate.
if (json.jsonType(of: "lat").intValue == 2) && (json.jsonType(of: "lon").intValue == 2) {
print("Coordinates: \(json.string(of: "lat")!), \(json.string(of: "lon")!)")
}
else {
print("Coordinates: unavailable")
}
}