Take the 2-minute tour ×

How do I get the url from a youtube video that is being played in a UIWebView?

share|improve this question
add comment

1 Answer

Once the YouTube video was loaded into the webView, I created a button that the user can tap to copy the URL to a text field on the same page. The trick is to get the innerHTML of the page and then look for the YouTube ID. With this ID I then put it into a full url so that the user can save the link and play back the video at a later date without having to look for that video again on the YouTube site. (BTW, I have my own displayAlert that takes the given message and displays it to the user when there isn't a video loaded in the UIWebView or there are many videos loaded) Here is the code:

-(IBAction)copyURLAction {
    if (webView) {
        NSString* htmlString = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];
        if (htmlString) {
            NSString *youTubeID = @"data-youtube-id=\"";
            int position = [htmlString rangeOfString:youTubeID].location + [youTubeID length];
            if (position > 1) {
                htmlString = [htmlString substringFromIndex:position];
                position = [htmlString rangeOfString:@"\""].location;
                htmlString = [htmlString substringToIndex:position];
                NSString* tempPrefix = @"http://m.youtube.com/watch?v=";
                NSString *youTubeString = [tempPrefix stringByAppendingString:htmlString];
                textFieldView.text = youTubeString;
            } else {
                [[SharedObjectsSingleton sharedInstance] displayAlert:@"Can't Copy URL" :@"Can only copy the URL when a single video is being displayed."];
        } else {
            [[SharedObjectsSingleton sharedInstance] displayAlert:@"Can't get URL" :@"Nothing to copy."];
share|improve this answer
add comment

Your Answer


