Search code examples
iosuiwebviewyoutubeuiwebviewdelegate

How to get the url of currently playing video in UIWebview


Is there any way to get the link of currently playing video.I am loading m.youtube.com .For some videos it is not even entering the delegates.I tried using a NStimer as well.But for some videos it is not the clicked url


Solution

  • There is a hacky way of doing it by listening for the AVPlayerItemBecameCurrentNotification notification. This notification is fired when a UIWebView shows the media player, and it sends an AVPlayerItem as the notification's object.

    For example:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemBecameCurrent:)
                                                 name:@"AVPlayerItemBecameCurrentNotification"
                                               object:nil];
    
    
    -(void)playerItemBecameCurrent:(NSNotification*)notification {
        AVPlayerItem *playerItem = [notification object];
        if(playerItem == nil) return;
        // Break down the AVPlayerItem to get to the path
        AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
        NSURL *url = [asset URL];
        NSString *path = [url absoluteString];
    }
    

    This works for any video (and audio). However, I noticed you mentioned YouTube - it's worth pointing out Apple WILL reject your app if it has the ability to download YouTube videos AT ALL, because it's against YouTube's Terms of Service.