Measuring Ping in iOS Apps: A Simple Solution

Vitaliy Podolskiy
2 min readMay 14, 2023

--

Today, I would like to share with you a simple way to measure the ping to a selected server in an iOS application. This code displays the actual ping to the server.

Design element example
Design element example

To measure the ping, we will use a URL request with the “HEAD” method, which sends the minimum amount of data and does not load the page content. As a result, we get the response time from the server, which allows us to determine the ping.

Our code uses the asynchronous function measure(to:), which takes the server address as a string parameter. Using the guard function, we check to see if we can generate a correct URL from this string. If we can’t create a URL, we throw the NetError.cannotCreateURL exception.

Then we create a URLRequest with the HEAD method for this URL and execute it with the URLSession.shared.data(for:) method. If the request is successful, we measure the time it takes to complete the request and receive the data on the device. If the request fails, we throw the NetError.pingFailure exception.

Finally, we return the request execution time as an integer, which corresponds to the ping to the server. Note that we multiply this value by 100 to get the result in milliseconds.

enum NetError: Error {
case pingFailure
case cannotCreateURL
}

struct Ping {
static func measure(to host: String) async throws -> Int {
guard let url = URL(string: host) else {
throw NetError.cannotCreateURL
}

var request = URLRequest(url: url)
request.httpMethod = "HEAD"

do {
let startTime = CFAbsoluteTimeGetCurrent()
_ = try await URLSession.shared.data(for: request)
let endTime = CFAbsoluteTimeGetCurrent()
return Int(endTime - startTime) * 100
}
catch {
throw NetError.pingFailure
}
}
}

The code is written using the new asynchronous functionality of Swift and requires iOS 13 or later. However, you can use similar code on earlier versions of iOS by using the standard URLSession methods.

I hope this code helps you create a simple and efficient way to measure ping in your iOS application. If you have any questions or suggestions, please leave a comment below. Thanks for your attention!

Follow our news!

Best regards,
Vitaliy

--

--

Vitaliy Podolskiy

I have been developing applications for many years. More than 40 completed commercial projects.