Knowing when a YouTube video starts playing from within a UIWebView

删除回忆录丶 提交于 2019-12-03 21:33:19

I believe that this could work on iOS7 via the new JavaScriptCore framework (although I've not personally tested it).

What I've tested though and it seems to be working fine is this approach:

Instead of registering a listener on different event changes, you could have a timer that queries the state of the player every second.

First, you could define some states on the player class (that would correspond to Youtube's states) (in header file):

typedef NS_ENUM(NSInteger, YoutubeVideoState){
    YOUTUBE_VIDEO_STATE_UNSTARTED   = -1,
    YOUTUBE_VIDEO_STATE_ENDED       = 0,
    YOUTUBE_VIDEO_STATE_PLAYING     = 1,
    YOUTUBE_VIDEO_STATE_PAUSED      = 2,
    YOUTUBE_VIDEO_STATE_BUFFERING   = 3,
    YOUTUBE_VIDEO_STATE_VIDEO_CUED  = 5
};

Then you could have a readonly property to get the state (also in header file):

@property (nonatomic, readonly) YoutubeVideoState state;

which would be implemented like:

- (YoutubeVideoState)state
{
    return (YoutubeVideoState)[[self.webView stringByEvaluatingJavaScriptFromString:@"getPlayerState()"] integerValue];
}

Now you can just ask from your instance to get you the current state in each timer invocation like:

YoutubeVideoState currentState = myPlayerInstance.state;

and possibly decide on your next action via a switch or an if statement:

if (currentState == YOUTUBE_VIDEO_STATE_PLAYING) {
    // Start your engines!
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!