Swift
Swift
ip2location.io GeoLocation API
See more Geolocation Examples
Demonstrates how to lookup Geolocation data for an IPv4 address using the ip2location.io GeoLocation API.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let http = CkoHttp()!
// Note: This is not a real API key. Replace with your own...
http.setUrlVar(name: "api_key", value: "2C312FBC9E667E5A0211F5152E5A1333")
http.setUrlVar(name: "ip_address", value: "8.8.8.8")
// Note: When first creating an ip2location.io account, make sure to at least subscribe to the free access.
// Otherwise your API key will not yet work..
var jsonStr: String? = http.quickGetStr(url: "https://api.ip2location.io/?key={$api_key}&ip={$ip_address}&format=json")
if http.lastMethodSuccess == false {
print("\(http.lastErrorText!)")
return
}
let json = CkoJsonObject()!
json.emitCompact = false
success = json.load(json: jsonStr)
print("\(json.emit()!)")
// Sample output:
// Use this online tool to generate parsing code from sample JSON:
// Generate Parsing Code from JSON
// {
// "ip": "8.8.8.8",
// "country_code": "US",
// "country_name": "United States of America",
// "region_name": "California",
// "city_name": "Mountain View",
// "latitude": 37.405992,
// "longitude": -122.078515,
// "zip_code": "94043",
// "time_zone": "-07:00",
// "asn": "15169",
// "as": "Google LLC",
// "is_proxy": false
// }
var ip: String? = json.string(of: "ip")
var country_code: String? = json.string(of: "country_code")
var country_name: String? = json.string(of: "country_name")
var region_name: String? = json.string(of: "region_name")
var city_name: String? = json.string(of: "city_name")
var latitude: String? = json.string(of: "latitude")
var longitude: String? = json.string(of: "longitude")
var zip_code: String? = json.string(of: "zip_code")
var time_zone: String? = json.string(of: "time_zone")
var asn: String? = json.string(of: "asn")
var v_as: String? = json.string(of: "as")
var is_proxy: Bool = json.bool(of: "is_proxy")
}