Getting elapsed time for YouTube videos on iOS

Recently I came across this problem to keep track of how much time elapsed for YouTube video while working on one of our apps. The reason being, we were looking for user engagement score and we wanted to analyze the time for which user was engaged in watching YouTube video in terms of seconds.

For regular videos it was straightforward as we would keep a JavaScript callback for timeupdate. However, for YouTube videos there was no such mechanism. It was completely embedded in the iframe with no possible way to keep track of time.

The requirement was to present video on the UIWebView and when user leaves the page, get the total time duration for which user watched the video and report that to analytics services.

Then fortunately my colleague found a great link to Youtube Player API reference where we could query for current video time periodically by querying on YT.Player object which was responsible for handling videos. We need to specify following parameters to player

  • width - width of YouTube player
  • height - height of YouTube player
  • video id - Identifier of YouTube video. For e.g. if YouTube link to video is https://www.youtube.com/watch?v=4OCfsRBSVVw, its video identifier will be 4OCfsRBSVVw
  • events -

 {
 'onReady': <Callback when player is ready>,
 'onStateChange': <Callback when player state changes>
 }

You can load this JavaScript code on UIWebView with related input parameters as specified above.

As documented above, the elapsed time in seconds can be retrieved with following property,

Say, if player is an instance of YT.Player, this can be done as follows :


player.getCurrentTime()

You can maintain a function which returns this value and then when you are ready to get current elapsed time, it can be executed with following JavaScript code.


NSString elapsedTime = webView.stringbyevaluatingjavascriptfromstring("timeElapsed()");

Full JavaScript code to display YouTube video on UIWebView with YTPlayer can be found on This Gist on Github