Rectangle 27 8

Just use XCDYouTubeVideoPlayerViewController. It seamlessly adds youtube video to your app without the need of UIWebView.

It uses progressive download + MoviePlayer and AVFoundation frameworks. Just supply it with a youtube video ID and you are good to go.

It supports both full-screen & non full-screen and WORKS ON iOS SIMULATOR!!!

XCDYouTubeVideoPlayerViewController *videoPlayerViewController = [[XCDYouTubeVideoPlayerViewController alloc] initWithVideoIdentifier:@"9bZkp7q19f0"];
[self presentMoviePlayerViewControllerAnimated:videoPlayerViewController];

i add this library using pod, and which header i want to use for this.

#import <XCDYouTubeKit/XCDYouTubeKit.h>

ios - Play YouTube videos in iPhone app without using UIWebView? - Sta...

iphone ios uiwebview youtube mpmovieplayercontroller
Rectangle 27 2

Here is another way to load the youtube video into your app. First, put a UIWebView into your interface and size it to how big you want the video should show (there will be a button to make it full screen), then make an IBOutlet to it, so you can change its properties of hidden (to make it pop up and go away) Here is some code. In the code there is a method used called webviewshow, this calls a simple method that basically just says webview.hidden = NO; webviewbutton.hidden = NO; Then there is a button that also pops up that makes the web view go away when tapped. Here is the code to load the youtube video into the web view

// Create your query ...
    NSString* searchQuery = [NSString stringWithFormat:@"];

    // Be careful to always URL encode things like spaces and other symbols that aren't URL friendly
    searchQuery = [searchQuery stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

    // Now create the URL string ...
    NSString* urlString = searchQuery;

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

    [webView loadRequest:request]; currentTimer= [NSTimer      scheduledTimerWithTimeInterval:2 target:self selector:@selector(webviewshow) userInfo:nil repeats:NO];;

It waits 2 seconds (usual wait time for most connections) until the web view is shown, so the page is loaded and the user does not have to watch it load.

Then when you want to make the video go away, make a method to close the web view like so

- (void) makewebviewGoAway {webview.hidden = YES; webviewbutton.hidden = YES;}

Hopefully, that was helpful. IF you need further help or explanation, just comment off of this.

i m doing it programmatically and i want only this specific video to show i dont to show other videos of youtube or search query for videos. On the main window have uibutton when that button is pressed only then uiwebview displays youtube video to play

the code I gave you is exactly what your looking for then.

Thanks!!! I used this method over loading a whole HTML string and it works a lot better

iphone - Youtube video in UIWebview not working - Stack Overflow

iphone objective-c ios uiwebview youtube
Rectangle 27 7

For Vimeo player you can check this link it plays the video in real player and if you want to run the video in uiwebview,here is the code for that

Pass you URL of YouTube Video in urlStr.

//In .h file
UIWebView *videoView;
// In .m file

videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 385)];

[self embedYouTube :urlStr  frame:CGRectMake(0, 0, 320, 385)];

[self.view addSubview:videoView];

// methos to embed URL in HTML & load it to UIWebView

- (void)embedYouTube:(NSString*)url frame:(CGRect)frame


NSString* embedHTML = @\


<style type=\text/css\>\

body {\

background-color: transparent;\

color: white;\



</head><body style=\margin:0\>\

<embed id=\yt\ src=\%@\ type=\application/x-shockwave-flash\ \

width=\%0.0f\ height=\%0.0f\></embed>\


NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];

if(videoView == nil) {

videoView = [[UIWebView alloc] initWithFrame:frame];

[self.view addSubview:videoView];


[videoView loadHTMLString:html baseURL:nil];


Hope This Will Help You Out. If this doesn't help you out please check out these links:-

Nope not yet. @popeye

@Avijit you can check this link for If still didn't work let me know.

When I used your vimeo link it just played using the default player in iPhone not within the webview(as I expected). Not getting any useful way to play the video within the webview :( .

ios - How to play youtube/vimeo video within the application in iPhone...

ios objective-c youtube uiwebview vimeo
Rectangle 27 6

i've tested this on iOS6 with UIWebView loading video webpage, and it does the job. the audio session needed to be set as AVAudioSessionCategoryPlayback in order to be played in background.

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

Thanks! Setting the audio session category to AVAudioSessionCategoryPlayback is all that is necessary, to make AirPlay work properly from a video inside a UIWebView. The video continues to play on Airplay even after the device goes to sleep. The mediaPlaybackAllowsAirPlay property is YES by default.

ios - Play video in UIWebview background on Airplay - Stack Overflow

ios airplay apple-tv
Rectangle 27 2

-(void)viewWillDisappear is now (iOS6) called if you play a video in fullscreen mode

try registering for UIMoviePlayerControllerDidEnter*(/Exit)*FullscreenNotification and modifying viewWillDisappear like UIWebView Movie Player getting dismissed iOS 6 bug

This is the correct solution. Actually it's logical cos video is presented in some kind of a modalView which is pushed above webView. Thanks!

iphone - Playing youtube video fullscreen in UIWebView on iOS 6 - Stac...

iphone ios uiwebview youtube fullscreen
Rectangle 27 2

I had a similar problem, and discovered that the fullscreen video is added as a view to the window's rootViewController, which was not the view controller that contained the UIWebView. After setting window.rootViewController the video opened on top of the UIWebView as expected.

Thanks for the tip, How did you go about changing it in the code?

iphone - Watching Vimeo videos in UIWebView on iOS - Stack Overflow

iphone ios video uiwebview vimeo
Rectangle 27 1

Use the Video tag with this options

<video id="player" class="video" width="80%" height="500px" webkit-playsinline controls autoplay>
<source src="ert.mp4" type="video/mp4">
        Your browser does not support the video tag.

html - How to play Video in UIWebView but it will not open in native m...

html ios iphone uiwebview html5-video
Rectangle 27 6

Mr.Yuvaraj.M your above code is correct. Please run the project in your iPhone/iPod touch device. The youtube videos may not support/not work in Simulator. Please check on this. Thanks.

ios - Play YouTube videos in iPhone app without using UIWebView? - Sta...

iphone ios uiwebview youtube mpmovieplayercontroller
Rectangle 27 2

you can't run files from local memory if you are using UIWebView. If you want your video to not play automatically, you have to enter code into your HTML file (I'm assuming the HTML files you are displaying are your own) to disable auto play for the video.

If you are using object, here is a sample code for you to follow

<object width="160" height="144">
<param name="autoplay" value="false">

<embed src="" width="160" height="144"
autoplay="false" controller="false"


No. You have mistaken me. First I tried with only the WebView which is playing the video automatically. Then I planned to use the Html

I want to play the videos in the WebView and that too the videos should start playing after the user clicks the play button.

if the URL/html file you're running on UIWebView isn't yours, then you have add in code in the viewDidLoad section to disable autoplay. If you want to play local files, you have to make your own HTML file and configure the setting internally. Not too sure by what you meant with "planned to use HTML" since your UIWebView should be using a html file(recommended) if you are planning to display vid on a webpage.

Actually the mp4 videos are playing in the WebView, but the thing is they are playing automatically. I created a project which has webview with embed html and the link passed in the embedHtml is internet link. That works great. But if I pass the local file NSUrl , then it is showing crossed play symbol. Anyway I am fed up of resolving this issue, I am using MPMoviePlayerController.

iphone - How to Embed a Local Video File Into Html to play in UIWebVie...

iphone objective-c ios cocoa-touch uiwebview
Rectangle 27 2

Everything I have read on the apple developers website seems to suggest that it will automatically play in full screen mode in safari. Now if they are using another app, as far as I know you do not have access to that apps UIWebViews properties. However, in an attempt to not be totally useless, here is a link to all of the methods you can query and you might find some useful information in there.

javascript - Detect if the UIWebView can play video inline on iPhone (...

javascript ios iphone uiwebview html5-video
Rectangle 27 9

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.

[[NSNotificationCenter defaultCenter] addObserver:self

-(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.

Thank you ,Its working.Still I am not able to get the current url corresponding to the video.Is there any way ?

@Jeff What do you mean? My example code above shows getting the URL as a NSURL and NSString. This is the URL of the video that is being played.

I am getting encoded url.I am asking about the youtube link of the vide

When you click on a video page, shouldStartLoadWithRequest: is called just like every other web page. The request contains the URL, which will be something like

ios - How to get the url of currently playing video in UIWebview - Sta...

ios uiwebview youtube uiwebviewdelegate
Rectangle 27 47

Apparently the problem was with the nil base url, when I changed it to resourceURL the autoplay worked.

[self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

The full code for autoplay youtube videos (again this code mostly based on this post I just changed it to load from a string instead of a file):

static NSString *youTubeVideoHTML = @"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%@', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) {; } </script> </body> </html>";  

- (void)playVideoWithId:(NSString *)videoId {
    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId];

    [self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

Hi Eyal: I'm having a problem with your solution. Autoplay isn't working (if I remove the call to playVideo(), things work, but without autoplay). It seems my problem is similar to the one found here:!topic/youtube-api-gdata/ . Any ideas? I've tried on Simulator and Device. I just get a "video loading" indicator indefinitely.

Figured it out! Make sure the mediaPlaybackRequiresUserAction property on your UIWebView is set to NO (default is YES)!

It is auto-playing nicely, but the video still opening the Youtube video as full screen (vertical) on my iPhone 5, using iOS6..any other ideas? Just to be clear, the small window appears first, then goes full screen once it begins playing.

@Eyal Thanks a lot after searching a lot I got this link and it worked for me. Also appreciate your question style. :)

@PavanMore glad I can help :)

ios - How to autoplay a YouTube video in a UIWebView - Stack Overflow

ios objective-c youtube uiwebview youtube-api
Rectangle 27 2

First of all you cannot set the volume using javascript check this doc and read Volume Control in JavaScript section. Found here.

[[NSNotificationCenter defaultCenter] addObserver:self

- (void)playerItemBecameCurrentNotif:(NSNotification*)notification {
    AVPlayerItem *playerItem = notif.object;
    AVPlayer *player = [playerItem valueForKey:@"player"];
    [player setVolume:0.0];

It works, thanks Muhammad. Do you know if this is a legit approach? I've seen other post saying that this is "hacky".

This is hacky because its a webview's internal notification. Recently i developed an app that is listening to this notification and app store review team approved it.

ios - How to play youtube video in UIWebView muted? - Stack Overflow

ios iphone youtube uiwebview
Rectangle 27 1

This is what I used in an App to show a YouTube video centered in my UIWebView.

let width: CGFloat = player.frame.size.width
let height = ceil((width / 16) * 9) // Assuming that the videos aspect ratio is 16:9

let htmlString = "<div style='text-align: center;'><script type='text/javascript' src=''></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){;}</script><iframe id='playerId' type='text/html' width='\(width)' height='\(height)' src='\(youtubeVideoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></div>"

Does this work with iOS? Or just browsers?

I used this in a Swift application.

ios - Center an embedded youtube video in a UIWebview Swift - Stack Ov...

ios iphone swift youtube uiwebview
Rectangle 27 2

Use following code to play a youtube video in the UIWebView

Here we required "embed link" :

  • Just open your youtube link in browser
<iframe width="640" height="390" src="" frameborder="0" allowfullscreen></iframe>
  • copy the link in "src" field, this is your embed link Now just put this embed link on the place of "YOU_TUBE LINK" in the following code: NSString *htmlString = [NSString stringWithFormat:@"<html><head><meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = yes, width = 320\"/></head><body style=\"background:#00;margin-top:0px;margin-left:0px\"><div><object width=\"320\" height=\"480\"><param name=\"movie\" value=\"YOUTUBE_LINK\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"YOUTUBE_LINK\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"320\" height=\"480\"></embed></object></div></body></html>"]; [self.webView_youTube loadHTMLString:htmlString baseURL:nil];

ios - How to autoplay a YouTube video in a UIWebView - Stack Overflow

ios objective-c youtube uiwebview youtube-api
Rectangle 27 77

The only way to have a youtube video play inside your own app is to create a UIWebView with the embed tag from Youtube for the movie you want to play as the UIWebView's content. UIWebView will detect that the embedded object is a Youtube link, and the web view's content will be the youtube preview for the video. When your user clicks the preview, the video will be shown in an MPMoviePlayerController. This is the technique described at the link that Muxecoid provided (how to play youtube videos within an application), and this is (as far as I know of) the only way to have a youtube video play within an application. You can still have the Youtube application launch by passing the youtube URL to -[UIApplication openURL:], but of course this closes your own application which is often undesirable.

Unfortunately, there's no way to directly play a youtube video with MPMoviePlayerController because youtube does not expose direct links to the video files.

Yup, that's the only way to play YouTube videos in your app. Spent 2 looking for alternatives. Quality is kinda bad, too.

Is there a possibility to get the PlaybackFinishReason and PlaybackState notifications in case of playing an youtube video as embeded ?

This isn't the only way. You can get the mp4 file from Youtube. I do that in my AirPlayer Python Project, which enables you to play youtube videos on your AppleTV. I will port this and use it in my current iOS project and post the code here when It's ready.

Unfortunately using a direct link is prohibited. Section II/10. in "Your API Client will not [...] access any portion of any YouTube audiovisual content by any means other than use of a YouTube player or other video player expressly authorized by YouTube;"

ios - Play YouTube videos with MPMoviePlayerController instead of UIWe...

ios video streaming youtube mpmovieplayercontroller
Rectangle 27 1

if you added .mp4 or compatible other videos to your application's bundle, you can reach its path like this;

[[NSBundle mainBundle] pathForResource:@"blalba" ofType:@"mp4"];

If your videos are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this;

NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);

After getting the url of video, you can put it to your WebView. But it will play in iphone's default Video Player i think.. good luck..

I can able to play the videos in UIWebView already . PLease check my update question now

iphone - How to Embed a Local Video File Into Html to play in UIWebVie...

iphone objective-c ios cocoa-touch uiwebview
Rectangle 27 8

<video controls>
    <source src="banane.m4v">

where controls is the magic word.

Having the same problem as Petr, can't get any .mp4's to work.

mp4 and .mov fiels not working

objective c - playing a local video in a uiwebview - Stack Overflow

objective-c ipad html5 video uiwebview
Rectangle 27 1

The iPhone has support for youtube videos, (hence the built in youtube player), other than that it supports only quicktime. There is no support for other formats: most sites use flash for video these days (inc youtube), but flash is not supported on the iPhone. I site embedding a youtube video will work, but one embedding a video hosted elsewhere will not (unless its quicktime)

Ok, you are right. But the problem wasn't with the iPhone UIWebView component, it was an website issue. I apologize for the confusion and appreciate your reply.

video content on iPhone Safari/UIWebView - Stack Overflow

iphone video uiwebview
Rectangle 27 3

1) Add pod in your project

pod 'youtube-ios-player-helper'

2) Add UIView in xib and change its class to YTPlayerView

@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
NSDictionary *playerVars = @{
                              @"playsinline"    : @1,
                              @"showinfo"       : @0,
                              @"rel"            : @0,
                              @"controls"       : @1,
                              @"origin"         : @"", // this is critical
                              @"modestbranding" : @1

[self.playerView loadWithVideoId:@"Youtube Video Id" playerVars:playerVars];

Im giving you the answer because that is what I went with. The others were close but didn't work exactly as I needed it to do. Thank you. You have to do it a bit different with swift than what is posted on the website because they only use objective c there

Consider using Objective-C in swift.

ios - Center an embedded youtube video in a UIWebview Swift - Stack Ov...

ios iphone swift youtube uiwebview