Validate and Get Location Information from an IP Address in Swift

Cloudmersive
2 min readApr 14, 2021

Did you know that you can learn a lot about users by checking out their IP address? That little string of numbers that composes an IP address contains a wealth of information that can be used to better understand your client base, as well as identify potential threats. In the following tutorial, we will demonstrate how you can use an API in Swift to extract data from an IP address. It’s a simple process that can provide valuable results.

All you’ll need to perform the validation is the IP address and your API key; if you need to retrieve your API key, you can quickly register for a free account on the Cloudmersive website.

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)let parameters = "\"<string>\""
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://api.cloudmersive.com/validate/ip/intelligence")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()

And voila! You will receive an instant result indicating if the IP address is a known threat, bot, or Tor exit node, as well as location information such as country name/code, city, currency, latitude, longitude, and more.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.