Is there a way to measure latency in iOS?

2.1k views Asked by At

The problem I'm trying to solve is I would like to have a way to measure network latency and notify users when high latency situations occur. My app allows users to stream audio or video content from online sources and while playback is possible on 3g and even EDGE speeds in my testing, spikes in latency can cause hangups in usability. When this occurs I'd like to be able to alert the user the cause of these problems.

I've gone back to looking into Apple's Reachability sample code and it still does not help. I'll refer back to an issue filed over a year ago (http://openradar.appspot.com/13982938)

Assuming I start with a strong connection, I can set a custom profile in the network link conditioner that would drop 100% of packets sent, and the reachability code in the sample app does not change the positive result. It still tells me I have a connection even though no packets get through.

Are there any reliable values I can KVO or otherwise listen to, in order to get this information?

2

There are 2 answers

0
matt On BEST ANSWER

My app allows users to stream audio or video content from online sources

Some built-in ways of streaming tell you what's going on. If you're using AVPlayerItem, properties such as playbackLikelyToKeepUp and the accessLog, along with notifications such as AVPlayerItemPlaybackStalledNotification, can be helpful in keeping you abreast of any issues.

0
Avt On

The easiest way (and probably the only one that really works) is to store time value when you send a request and evaluate latency when you receive a response. You can check how AFNetworkActivityLogger solves this here https://github.com/AFNetworking/AFNetworkActivityLogger/blob/master/AFNetworkActivityLogger/AFNetworkActivityLogger.m

The most important lines for you are

objc_setAssociatedObject(notification.object, AFNetworkRequestStartDate, [NSDate date], OBJC_ASSOCIATION_RETAIN_NONATOMIC);

when request is sent and

NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:objc_getAssociatedObject(notification.object, AFNetworkRequestStartDate)];

when response is received.

How to integrate this logic to your code depends on what do you use to get streamed video.