Video in UIView (or UIWebView) - ios

I would like to know if I can play a video in UIView?
I want to play a video in a small UIView (say 100 x 100 ) which should be played automatically when the UIView loads.
First I would say what I tried out ... It would be really helpful if the experts ( I am a 2 week old baby in IOS development & Obj- C) to confirm whether the route I am heading is right..
I created a UIWebView and and tried to embed a video in it using HTML video tag (html5)
For the UIWebview I set the allowInlineMediaPlayback to YES and mediaPlaybackRequiresUserAction to NO ... Also in the HTML code, for the video tag, I used - webkit-playsinline.
Any help is much appreciated.
Update
This is my code with my html block ... I did add the play video JS .... But when I run the app in simulator , I do not get the video , only get audio.
NSString *embedHTML = #"\
<!DOCTYPE HTML>\
<html>\
<head>\
<script type=\"text/javascript\">\
function playvideo() {\
var myVideo=document.getElementsByTagName('video')[0];\
myVideo.play();\
myVideo.webkitExitFullscreen();\
myVideo.height = 120;\
myVideo.width = 120;\
}\
</script>\
</head>\
<body onLoad = \"playvideo()\" >\
<video id=\"player\" webkit-playsinline width=\"140\" height=\"140\">\
<source src=\"file:///Users/Shilpa/Desktop/Movie Player/MoviePlayer-ios4-Next/Movie-1.mp4\"/>\
</video>\
</body>\
</html>";
webView = [[UIWebView alloc] initWithFrame:CGRectMake(100.0, 170.0, 150.0, 150.0)];
[webView setOpaque:YES];
NSString *html = [NSString stringWithFormat:embedHTML, webView.frame.size.width, webView.frame.size.height];
[webView loadHTMLString:html baseURL:nil];
webView.allowsInlineMediaPlayback = YES;
webView.mediaPlaybackRequiresUserAction = NO;
webView.transform = CGAffineTransformMakeRotation(3.14/2);
[moviePlayerWindow addSubview:webView];

HTML Video tag, might needs an action via JavaScript,
try to put following code in your html page,
<body onload = playvideo() >
and see the magic :)
i believe, only to play the video you are using WebView, but you can use the QTView also to do the same.

Related

Is it possible to play a YouTube video on iOS without revealing/adding a view, while still following YouTube's Terms of Service?

I have a UITableView full of thumbnails of YouTube videos, and when they tap on one I want to start playing the YouTube video full screen automatically without the user seeing a view being added or having to interact any further than tapping the thumbnail.
Basically, I don't want to see the YouTube video player with that red play icon at all.
I was planning to use youtube-ios-player-helper/YTPlayerView to accomplish this, and I understand it just employs a UIWebView but I can't seem to figure out how to get it to work.
If I create an instance variable on my class, set myself as the delegate and select a random video for watching:
let YouTubePlayer = YTPlayerView()
override func viewDidLoad() {
super.viewDidLoad()
YouTubePlayer.delegate = self
YouTubePlayer.loadWithVideoId("apKJikXWU2g")
...
}
and then when the delegate method gets called:
func playerViewDidBecomeReady(playerView: YTPlayerView!) {
YouTubePlayer.playVideo()
}
But most of the time it either crashes in my AppDelegate with this message:
Nov 5 23:34:44 rtcreporting[73827] : logging starts...
Nov 5 23:34:44 rtcreporting[73827] : setMessageLoggingBlock: called
Or it will work if I disable breakpoints but I get a ton of Auto Layout constraint complaint messages before the video plays, indicating something is angry on some level.
Is this because I'm using a UIView subclass without actually adding it to the view hierarchy?
How would I accomplish the behaviour of autoplaying a YouTube video after a certain event without revealing a kludgy intermediary view?
Here you go, you don't have to see the youtube logo.
Define youtube iFrame, You'll need to replace the '%#' part with your youtube Video ID later when you supply to a UIWebView
#define youtubeVideoPlayUrl
#"<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%f', height:'%f', videoId:'%#', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>"
Define a UIWebView object of name videoWebView to display the iFrame. You can set the height and width to be zero so it doesn't block your screen. It's like a hidden iFrame.
self.videoWebview = [UIWebView alloc] init];
I suggest you to use your own default Image and a play button on top of the image to avoid having to show 'Youtube' video logo. Once you've done that, use the following code to play the youtube video full screen
- (void)onPlayYouTubeVideo:(UIButton *)sender
{
NSString *youtubeVideoID = YOUR_YOUTUBE_VIDEO_ID;
NSString *html = [NSString stringWithFormat:youtubeVideoPlayUrl,
_videoWebView.frame.size.width, _videoWebView.frame.size.height, youtubeVideoID];
_videoWebView.mediaPlaybackRequiresUserAction = NO;
_videoWebView.delegate = self;
[_videoWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}
I'm using like this for a hotel booking app.
I've created a demo app for you.
Source code to load webView html taken from: http://iphoneincubator.com/blog/audio-video/how-to-play-youtube-videos-within-an-application
ViewController header file
#interface ViewController : UIViewController
#property (nonatomic, strong) UIWebView *webView;
#end
ViewController implementation file
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
self.webView.layer.borderWidth = 1.0;
self.webView.layer.borderColor = [UIColor redColor].CGColor;
self.webView.backgroundColor = [UIColor blackColor];
self.webView.center = self.view.center;
[self.view addSubview:self.webView];
NSString* embedHTML = #"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<embed id=\"yt\" src=\"%#\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSURL *url = [NSURL URLWithString:#"https://www.youtube.com/watch?v=K14RnTVt194"];
NSString* html = [NSString stringWithFormat:embedHTML, url, self.webView.frame.size.width, self.webView.frame.size.height];
[self.webView loadHTMLString:html baseURL:nil];
}
You should see this:
When you press the play button it goes full screen.
You probably want to create a method that accepts a URL to the youtube video in your custom cell class.
Then in the cellForRowAtIndexPath: method of your View Controller, you can call your custom cell loadYouTubeVideoWithURL: method to load the Youtube video url from your data source.
The YouTube Helper Library is definitely a nice way to embed Youtube in your iOS application while following YouTube's Terms of Service.
Regarding the Auto Layout constraints log warnings,
Is this because I'm using a UIView subclass without actually adding it to the view hierarchy?
These errors have nothing to do with your implementation and are easily reproducible.
You can create an empty iOS 8 project, add a UIWebView in your interface and try to load a Youtube page.
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"YOUTUBE_URL"]]];
You'll get the same Auto Layout constraints log messages that you got when using the YouTube Helper Library.
If you take a closer look at the elements having Auto Layout constraints problems, you'll see AVAudioOnlyIndicatorView, AVUnsupportedContentIndicatorView, AVExternalPlaybackIndicatorView, etc. The constraints with warnings are not related to views you created but are related to Apple's internal views structure. It has nothing to do with the YouTube Helper Library or your implementation.
You should definitely file a report: https://bugreport.apple.com
These warnings won't get your app rejected or lessen your chance to get your app approved until the issue is fixed from Apple, especially if you can get the warnings using an empty project with a UIWebView loading any Youtube page.

iOS: How to disable or handle next and previous buttons in UIWebView HTML5 movie player

In my iOS Phonegap application, we are playing youtube video inside a UIWebView using a cordova plugin. Below is the code I am using to embed the youtube video in UIWebView. We are using iFrame tag to embed the video.
customWebView= [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 512, 374)];
customWebView.delegate=self;
customWebView.scrollView.bounces=NO;
[customWebView setOpaque:NO];
customWebView.backgroundColor = [UIColor clearColor];
[webViewBackground addSubview:customWebView];
NSString* embedHTML = #"<html><head>\
<style type=\"text/css\">\body {\background-color: #000000;\
color: white;}</style></head><body style=\"margin:0\">\
<iframe width=\"512\" height=\"374\" src=\"%#\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
NSString* html = [NSString stringWithFormat:embedHTML, urlVideo];
[customWebView loadHTMLString:html baseURL:nil];
The video is playing perfectly fine. Both in normal mode and full screen mode. But in full screen mode, user can see the previous and next buttons. On click of next and previous button few times, the video is getting over and I can see only a black screen in webview.
Below are the screenshots.
Is there anyway we can disable the next and previous buttons in a iFrame video player? Or Is there any other way in which we can handle this?

UIWebView plays inline without autoplay not work by using iframe

I search this issue these days, but I can't find the solution. I use youtube with iframe in UIWebview. I want to make it playsinline without auto play by following code
embedHTML = [NSString stringWithFormat:#"\
<html>\
<body style='margin:0px;padding:0px;'>\
<script type='text/javascript' src='http://www.youtube.com/iframe_api'></script>\
<script type='text/javascript'>\
function onYouTubeIframeAPIReady()\
{\
ytplayer=new YT.Player('playerId')\
}\
</script>\
<iframe id='playerId' type='text/html' width='%d' height='%d' src='http://www.youtube.com/embed/%#?enablejsapi=1&rel=0&playsinline=1&autoplay=0' frameborder='0'>\
</body>\
</html>", (int)myWidth, (int)myHeight, _youtubeCode];
but it doesn't work. If using this code, then click webview to play the video, it allows to pop the video player to play the video.
I only success to play the video inline by following code, but it have to autoplay the video
embedHTML = [NSString stringWithFormat:#"\
<html>\
<body style='margin:0px;padding:0px;'>\
<script type='text/javascript' src='http://www.youtube.com/iframe_api'></script>\
<script type='text/javascript'>\
function onYouTubeIframeAPIReady()\
{\
ytplayer=new YT.Player('playerLiveId',{events:{onReady:onPlayerReady}})\
}\
function onPlayerReady(a)\
{ \
a.target.playVideo(); \
}\
</script>\
<iframe id='playerLiveId' type='text/html' width='%d' height='%d' src='http://www.youtube.com/embed/%#?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'>\
</body>\
</html>", (int)myWidth, (int)myHeight, _youtubeCode];
I need your help, please. btw, sorry about my english.
Did you try adding the following:
webView.allowsInlineMediaPlayback = YES;
to your UIWebview code?
I have the same problem. If using Youtube API to play video, it can plays inline normally. But if user presses big red icon, the player will goes to full screen. I fixed it by adding an overlay view and remove it after playing.
UIView *overlayer = [[UIView alloc] initWithFrame:ytWebView.bounds];
[overlayer setAutoresizingMask:(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)];
[overlayer setBackgroundColor:[UIColor clearColor]];
[ytWebView addSubview:overlayer];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(playVideo:)];
[overlayer addGestureRecognizer:tap];
self.overlayer = overlayer;
And inside your playVideo:, you use Youtube API to play video and remember to remove overlayer.
Hope that hep!

YouTube Embed player in Iframe doesn't work in iOS6

I really need your help. Working on an iOS app. I want to play youtube. I understood from reading many many blogs and posts, that we need to use an iframe in order to play a youtube video.
However, on some videos I get: "This video contains content from XYZ. It is restricted from playback on certain sites. Watch on YouTube"
I read this question: Youtube in iOS5 - done button Tapped which gives the link to youtube api: https://developers.google.com/youtube/player_parameters
They recommend to use the iframe. the example for youtube site is:
<iframe id="ytplayer" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&origin=http://example.com"
frameborder="0"/>
The code I used:
<!DOCTYPE html>
<html>
<head>
<style>
* {
border:0;
margin:0;
}
</style>
</head>
<body>
<iframe webkit-playsinline id="player" type="text/html" width="320" height="180" src="http://www.youtube.com/embed/rEevIL1Wpcg?enablejsapi=1&playsinline=1&autoplay=1" frameborder="0">
</iframe>
</body>
</html>
Can someone help me understand it? I check the embedded flag to be true, they are all clips that are allowed to play on mobile devices.
Example for videos that works on the device:
http://www.youtube.com/watch?v=rEevIL1Wpcg&feature=youtube_gdata
http://www.youtube.com/watch?v=KzGe7pbGUiM
Example for videos that don't work on the device and bring up the error msg:
http://www.youtube.com/watch?v=1vhFnTjia_I&feature=youtube_gdata
http://www.youtube.com/watch?v=sxkiA0IjBZ0&feature=youtube_gdata
you can use webview as youtube player
Try Below Code it is working for me
in .h file
#property (strong, nonatomic) UIWebView *webView;
and in your .m file
NSString *videoURL = #"http://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&origin=http://example.com";
// if your url is not in embed format or it is dynamic then you have to convert it in embed format.
videoURL = [videoURL stringByReplacingOccurrencesOfString:#"watch?v=" withString:#"embed/"];
NSRange range = [videoURLString rangeOfString:#"&"];
#try {
videoURLString = [videoURLString substringToIndex:range.location];
}
#catch (NSException *exception) {
}
// here your link is converted in embed format.
NSString* embedHTML = [NSString stringWithFormat:#"\
<html><head>\
<style type=\"text/css\">\
iframe {position:absolute; top:50%%; margin-top:-130px;}\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<iframe width=\"100%%\" height=\"240px\" src=\"%#\" frameborder=\"0\" allowfullscreen></iframe>\
</body></html>",videoURL];
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:self.webView];
[self.webView loadHTMLString:embedHTML baseURL:nil];
Here you can change webview frame as you want and also can change videoUrl.
There are two concepts, embeddable and syndicated.
iOS devices use iframe so they basically embed.
Android devices that use player API can check syndicated.
When you do a search->list, you can set videoEmbeddable and videoSyndicated to true.
Or if you are iterating through videos, for each video, you can do a video->list call with video id and check status.embeddable in the response.
Here is a blog post about this topic, even though examples are in v2, information is still relevant.

UIWebView youtube iframe api autoplay/playsinline quit working in iOS7

This code has worked really well to auto-play video inline in an iOS 6 uiwebview. However, I upgraded to iOS 7 and now my video will not auto-play. Sometimes video will auto-play and sometimes it won't. It will auto-play about 10% of the time. Most of the time I get a spinning wheel. If I remove &playsinline=1 from the src tag it will auto-play fullscreen (not what I want). I spent a lot of time creating a custom player for this app and now it won't work correctly. Any help is greatly appreciated.
_youTubeWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 184)];
_youTubeWebView.delegate = self;
_youTubeWebView.scrollView.bounces = NO;
_youTubeWebView.allowsInlineMediaPlayback = YES;
_youTubeWebView.mediaPlaybackAllowsAirPlay = YES;
_youTubeWebView.mediaPlaybackRequiresUserAction = NO;
[self.view addSubview:_youTubeWebView];
NSString* embedHTML = [NSString stringWithFormat:#"<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){ a.target.playVideo(); }</script><iframe id='playerId' type='text/html' width='%#' height='%#'src='http://www.youtube.com/embed/%#?enablejsapi=1&rel=0&playsinline=1&controls=0&showinfo=0' frameborder='0'></body></html>", w, h, videoId];
[_youTubeWebView loadHTMLString:embedHTML baseURL:nil];
Here's a link to a quick test file. videoPlayerTest.zip
This sounds like the following open bug against the Youtube iframe player API:
Issue 5204: js iframe api playVideo() doesn't play video in iOS 7
http://code.google.com/p/gdata-issues/issues/detail?id=5204
You can fix the autoplay behavior by changing the baseURL to:
[[NSBundle mainBundle] resourceURL]

Resources