My application is a quizz game. The user has a limited time to answer the question.
A timer is used for that. When the time runs out, a simple sound is triggered.
NSTimer *m_timer;
In function viewDidAppear:
m_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(decrementSpin) userInfo:nil repeats:YES];
In my fisrt version, I encountered the following situation:
If during a question, an incoming call interrupts the game, the timer was still counting during the call.
I fixed this problem by adding in function viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(appDidEnterInBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
- (void)appDidEnterInBackground:(NSNotification *)notification {
[[SoundManager sharedManager]stopMusic:NO];
[m_timer invalidate];
m_timer = nil;
}
- (void)appWillEnterForeground:(NSNotification *)notification {
if(m_timer) {
[m_timer invalidate];
m_timer = nil;
}
//NSLog(#"%d", self.TimerbackgroundView.percent);
m_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(decrementSpin) userInfo:nil repeats:YES];
}
The function decrementSpin updates the clock image and plays the sound if the player has run out of time.
Everything works well.
Since my last version, I added a feature. The user can report a question (for incorrect content) by pressing a button.
When a button is pressed it opens the mail app with a prefilled content.
MFMailComposeViewController*mailComposerVC = [[MFMailComposeViewController alloc] init];
if ([MFMailComposeViewController canSendMail]) {
mailComposerVC.mailComposeDelegate = self;
[mailComposerVC setToRecipients:#emailAddress];
[mailComposerVC setSubject:emailSubject];
[mailComposerVC setMessageBody:emailBody isHTML:NO];
[self presentViewController:mailComposerVC animated:YES completion:^{
}];
}
else{
NSLog(#"Unable to send message");
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
[controller dismissViewControllerAnimated:YES completion:^{
}];
}
It seems that my application doesn't handle correctly when the user sends the mail and returns to the Question page.
The timer doesn't pause (like the incoming call case), and in addition, when the Question page re-appears the clock-image shows the initial image (exactly like when the page appears for the first time)
This bug causes the sound (the one triggered when the user runs out of time) to be played during the next Page.
The only thing that comes in my mind that the events notified by UIApplicationDidEnterBackgroundNotification and UIApplicationWillEnterForegroundNotification are not covered in the case of MFMailComposeViewController.
Any idea ?
You are correct. The app is still running the in the foreground.
So a possible solution would be to execute the same code of appDidEnterInBackground when opening the Mail.app, and to do the same as appWillEnterForeground in the body of
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
[controller dismissViewControllerAnimated:YES completion:^{
}];
}
What do you think ?
AVPlayer video not resuming from where it left, instead video starts from beginning. Here is my code.Can anyone help me??
-(void)appEnteredForeground:(NSNotification*)notification {
if(playerViewController.player.status == AVPlayerStatusReadyToPlay &&
playerViewController.player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
total_duration = self.playerViewController.player.currentItem.duration;
[self.playerViewController.player seekToTime:currentTime];
[_playerViewController.player play];
}
}
-(void)appEnteredBackground:(NSNotification*)notification {
[playerViewController.player pause];
currentTime = [playerViewController.player currentTime];
[playerViewController.player seekToTime:currentTime];
}
1.It's seek to time problem, when u ask it to seek to time, it can't be done as it's already in background. Why did u seek to time when u enter background? pause should do just fine. remove the following line.
[playerViewController.player seekToTime:currentTime];
2.you had better pause in resign active notification instead of background notification. because the last one shall be triggered in a few seconds later after pressing the home button
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(resignActive) name:UIApplicationWillResignActiveNotification object:nil];
}
- (void)becomeActive {
NSLog(#"active");
if(playerViewController.player.status == AVPlayerStatusReadyToPlay &&
playerViewController.player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
total_duration = self.playerViewController.player.currentItem.duration;
[self.playerViewController.player seekToTime:currentTime];
[_playerViewController.player play];
}
}
- (void)resignActive {
NSLog(#"resign active");
[playerViewController.player pause];
currentTime = [playerViewController.player currentTime];
}
I am facing an issue with MPMoviePlayerController in iOS 7. I enter the fullscreen and then click (just a single tap) on seek forward button (>>|) , and the video playback ends and gives a black screen with a text "Loading" on the header.
I registered notification for "MPMoviePlayerPlaybackStateDidChangeNotification".
**[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerPlaybackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:self.player];**
It does not get fired on a single click of seek forward button.
Also on registration of "MPMoviePlayerPlaybackDidFinishNotification"
**[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerPlaybackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];**
I get "MPMovieFinishReasonPlaybackEnded" event fired on that single click of seek forward button.
Any one knows the reason why? Is this a bug in apple?
I need to either stop this behavior of showing a black screen on single click , or just disable single click of seek forward button so that nothing happens.
Any one knows how to achieve this?
I fixed this by removing the MPMoviePlayer object completely, setting it to nil, removing it from it's superview and re-adding it using the original video Url. Code below:
- (void)addPlayerForUrl:(NSURL *)url {
self.player = [[MPMoviePlayerController alloc] initWithContentURL:url];
self.player.view.frame = self.videoView.bounds;
self.player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.player.controlStyle = MPMovieControlStyleDefault;
[self.videoView insertSubview:self.player.view atIndex:0];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerLoadStateDidChangedNotification:)
name:MPMoviePlayerReadyForDisplayDidChangeNotification
object:self.player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerPlaybackStateDidChangeNotification:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:self.player];
}
#pragma mark - Notifications
- (void)moviePlayerLoadStateDidChangedNotification:(NSNotification *)notification {
self.isVideoPreloaded = YES;
self.videoPlayButton.hidden = YES;
self.photoImageView.hidden = YES;
self.videoLoadingImageView.hidden = YES;
}
- (void)moviePlayerPlaybackStateDidChangeNotification:(NSNotification *)notification {
NSURL *url = self.player.contentURL;
switch (self.player.playbackState) {
case MPMoviePlaybackStateSeekingBackward:
case MPMoviePlaybackStateSeekingForward:
break;
case MPMoviePlaybackStatePlaying:
self.videoPlayButton.hidden = YES;
if (!self.isVideoPreloaded) {
self.videoLoadingImageView.hidden = NO;
[self.videoLoadingImageView startAnimating];
} else {
self.videoLoadingImageView.hidden = YES;
}
break;
case MPMoviePlaybackStatePaused:
case MPMoviePlaybackStateStopped:
self.videoPlayButton.hidden = NO;
self.videoLoadingImageView.hidden = YES;
[self.player endSeeking];
[self.player.view removeFromSuperview];
[self.player setFullscreen:NO];
self.player = nil;
[self addPlayerForUrl:url];
break;
default:
break;
}
}
Notice how I keep the NSURL, right before the switch statement in the moviePlayerPlaybackStateDidChangeNotification. That way, I can re-initialize and re-add the MPMoviePlayer object.
Btw, my mpmovieplayer is on a tableviewCell if you're wondering. Hope this helps and let me know if you have questions. Good luck!
MPMoviePlayerLoadStateDidChangeNotification will be called when you single tap on the fast-forward or rewind button. You should check the loadState and just give it the path to your video and prepareToPlay again.
- (void)moviePlayerLoadStateChanged:(NSNotification *)notification {
MPMoviePlayerController *moviePlayer = notification.object;
MPMovieLoadState loadState = moviePlayer.loadState;
if(loadState == MPMovieLoadStateUnknown) {
moviePlayer.contentURL = [NSURL fileURLWithPath:videoPath]
[moviePlayer prepareToPlay];
}
.....
}
The reason you're getting MPMovieFinishReasonPlaybackEnded is because playback reached the end of the video (sorry if this is obvious). So it seem's your seek forward actions are seeking all the way to the end of the video. You can check the playback state with MPMoviePlaybackStateSeekingForward.
A quick solution could be to create your own forward button that seek's ahead by a specified time (ie. 5 seconds). But perhaps this isn't the functionality you're looking for.
I didn't received any notifications for MPMoviePlayerController. What am I doing wrong?
I use following logic.
I'm begining to play youtube video in UIWebView. UIWebView calls a standard MPMoviePlayerController. I don't control MPMoviePlayerController because I didn't instantiate MPMoviePlayerController.
I run youtube's clip with autoplay (1 second delay):
[self performSelector:#selector(touchInView:) withObject:b afterDelay:1];
My code is:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(loadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playbackDidFinish:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
[self embedYouTube];
}
- (void)loadStateDidChange:(NSNotification*)notification
{
NSLog(#"________loadStateDidChange");
}
- (void)playbackDidFinish:(NSNotification*)notification
{
NSLog(#"________DidExitFullscreenNotification");
}
- (void)embedYouTube
{
CGRect frame = CGRectMake(25, 89, 161, 121);
NSString *urlString = [NSString stringWithString:#"http://www.youtube.com/watch?v=sh29Pm1Rrc0"];
NSString *embedHTML = #"<html><head>\
<body style=\"margin:0\">\
<embed id=\"yt\" src=\"%#\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
videoView.delegate = self;
for (id subview in videoView.subviews)
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
((UIScrollView *)subview).bounces = NO;
[videoView loadHTMLString:html baseURL:nil];
[self.view addSubview:videoView];
[videoView release];
}
- (void)webViewDidFinishLoad:(UIWebView *)_webView
{
UIButton *b = [self findButtonInView:_webView];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(touchInView:) object:b];
[self performSelector:#selector(touchInView:) withObject:b afterDelay:1];
}
- (UIButton *)findButtonInView:(UIView *)view
{
UIButton *button = nil;
if ([view isMemberOfClass:[UIButton class]]) {
return (UIButton *)view;
}
if (view.subviews && [view.subviews count] > 0)
{
for (UIView *subview in view.subviews)
{
button = [self findButtonInView:subview];
if (button) return button;
}
}
return button;
}
- (void)touchInView:(UIButton*)b
{
[b sendActionsForControlEvents:UIControlEventTouchUpInside];
}
UPDATE: I'm creating application that plays youtube's video. You can run playlist and you will see first video. When first video has ended, second video begins play automatically and so on.
I need to support ios 4.1 and above.
UPDATE2: #H2CO3 I'm trying to use your url-scheme, but it don't works. Delegate method didn't called on exit event. I added my html url to log.
It is:
<html><head> <body style="margin:0">
<script>function endMovie()
{document.location.href="somefakeurlscheme://video-ended";}
</script> <embed id="yt" src="http://www.youtube.com/watch?v=sh29Pm1Rrc0"
onended="endMovie()" type="application/x-shockwave-flash"
width="161" height="121"></embed>
</body></html>
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([[[request URL] absoluteString] hasPrefix:#"somefakeurlscheme://video-ended"])
{
[self someMethodSupposedToDetectVideoEndedEvent];
return NO; // prevent really loading the URL
}
return YES; // else load the URL as desired
}
UPDATE3
#Till, I cann't caught UIMoviePlayerControllerDidExitFullscreenNotification, but I found MPAVControllerItemPlaybackDidEndNotification. MPAVControllerItemPlaybackDidEndNotification appears when playback video is ended.
But I don't understand how do I catch onDone notifications?
There are no documented notifications sent by the UIWebView embedded movie player.
In fact, the closed implementation used within the UIWebView does differ from the public MPMoviePlayerController in many aspects (e.g. DRM).
The most important classes used for playing video content within that UIWebView are called MPAVController and UIMoviePlayerController. The latter one makes the player appear like the MPMoviePlayerController fullscreen interface.
In case you dare to risk a rejection by Apple, there are actually ways to still achieve what you are looking for.
NOTE
This is not documented and is subject to break on each and every new iOS release. It does however work on iOS4.3, 5.0 and 5.01, 5.1 and 6.0 and it may work on other versions as well.
I am not able to test this solution on iOS 4.1 and 4.2, so that is up to you to do. I highly suspect that it will work.
Fullscreen State
If, for example you are intending to react upon the user tapping the DONE button, you may be able to do it this way:
UPDATE The old version of this answer recommended to use UIMoviePlayerControllerDidExitFullscreenNotification whereas this new version (updated for iOS6) recommends using UIMoviePlayerControllerWillExitFullscreenNotification.
C-Language Level:
void PlayerWillExitFullscreen (CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
//do something...
}
CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
NULL,
PlayerWillExitFullscreen,
CFSTR("UIMoviePlayerControllerWillExitFullscreenNotification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
Objective-C Level:
- (void)playerWillExitFullscreen:(NSNotification *)notification
{
//do something...
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerWillExitFullscreen:)
name:#"UIMoviePlayerControllerWillExitFullscreenNotification"
object:nil];
I did draft both, C-Level and Objective-C-Level options because the best way to actually find out about all of this is to use C-Level (CoreFoundation) functions as shown at the end of my answer. If the sender of a notification does not use Objective-C (NSNotifications), you may actually not be able to trap them using the NSNotification-mechanics.
Playback State
For examining the playback state, look out for "MPAVControllerPlaybackStateChangedNotification" (as drafted above) and examine the userInfo which may look like this:
{
MPAVControllerNewStateParameter = 1;
MPAVControllerOldStateParameter = 2;
}
Further Reverse Engineering
For reverse engineering and exploring all the notifications sent, use the following snippet.
void MyCallBack (CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
NSLog(#"name: %#", name);
NSLog(#"userinfo: %#", userInfo);
}
CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
NULL,
MyCallBack,
NULL,
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
In iOS 4.3+ you can use the UIMoviePlayerControllerDidEnterFullscreenNotification and UIMoviePlayerControllerDidExitFullscreenNotification notifications:
-(void)viewDidLoad
{
...
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(youTubeStarted:) name:#"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(youTubeFinished:) name:#"UIMoviePlayerControllerDidExitFullscreenNotification" object:nil];
}
-(void)youTubeStarted:(NSNotification *)notification{
// your code here
}
-(void)youTubeFinished:(NSNotification *)notification{
// your code here
}
As far as I know, the implementation details of UIWebView (and all system classes made by Apple) are not to be relied upon when making a Cocoa Touch application. Maybe it's the case that an UIWebView's video player is not a standard MPMoviePlayerController class and it might have a totally different delegation/notification system, which is not supposed to be accessible by the user.
I suggest you to use the HTML5 element and detect the "onended" event of this tag:
<html>
<body>
<script>
function endMovie() {
// detect the event here
document.location.href="somefakeurlscheme://video-ended";
}
</script>
<video src="http://youtube.com/watch?v=aiugvdk755f" onended="endMovie()"></video>
</body>
</html>
In fact, from the endMovie JavaScript function, you can redirect to a bogus URL which you can catch in your -webView:shouldStartLoadWithRequest: (UIWebViewDelegate) method thus get notified that the video has ended:
- (BOOL) webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)req {
if ([[[req URL] absoluteString] hasPrefix:#"somefakeurlscheme://video-ended"]) {
[self someMethodSupposedToDetectVideoEndedEvent];
return NO; // prevent really loading the URL
}
return YES; // else load the URL as desired
}
Hope this helps.
Based on the #H2CO3 answer but with the iframe API. It was the only way I could make it work.
This doesn't use any private API which makes it more future proof.
Here's the code to embed your Youtube video. Check the API for more ways to customise this.
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '480',
width: '640',
videoId: 'aiugvdk755f',
events: {
'onStateChange': onPlayerStateChange
}
});
}
// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
endedMovie();
}
}
function endedMovie() {
// detect the event here
document.location.href="somefakeurlscheme://video-ended";
}
</script>
</body>
</html>
And this is how you get notified that the video ended (UIWebViewDelegate method).
- (BOOL) webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)req {
if ([[[req URL] absoluteString] hasPrefix:#"somefakeurlscheme://video-ended"]) {
[self someMethodSupposedToDetectVideoEndedEvent];
return NO; // prevent really loading the URL
}
return YES; // else load the URL as desired
}
in ViewDidLoad add the following code
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(VideoExitFullScreen:) name:#"UIMoviePlayerControllerDidExitFullscreenNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(VideoEnterFullScreen:) name:#"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
The following methods are for showing the message/functions for respective process of entering/exiting to/from full screen
- (void)VideoExitFullScreen:(id)sender{
// Your respective content/function for Exit from full screen
}
- (void)VideoEnterFullScreen:(id)sender{
// Your respective content/function for Enter to full screen
}
This works for me in iOS 6.1, it hides/removes other windows when the AVPlayerItemDidPlayToEndTimeNotification is received:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playerItemEnded:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
...
- (void)playerItemEnded:(NSNotification *)notification
{
for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
if (window != self.window) {
window.hidden = YES;
}
}
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(youTubeStarted:) name:UIWindowDidBecomeVisibleNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(youTubeFinished:) name:UIWindowDidBecomeHiddenNotification object:nil];
-(void)youTubeStarted:(NSNotification *)notification
{
// Entered Fullscreen code goes here..
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.fullScreenVideoIsPlaying = YES;
NSLog(#"%f %f",webViewForWebSite.frame.origin.x,webViewForWebSite.frame.origin.y);
}
-(void)youTubeFinished:(NSNotification *)notification{
// Left fullscreen code goes here...
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.fullScreenVideoIsPlaying = NO;
//CODE BELOW FORCES APP BACK TO PORTRAIT ORIENTATION ONCE YOU LEAVE VIDEO.
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
//present/dismiss viewcontroller in order to activate rotating.
UIViewController *mVC = [[UIViewController alloc] init];
[self presentViewController:mVC animated:NO completion:Nil];
// [self presentModalViewController:mVC animated:NO];
[self dismissViewControllerAnimated:NO completion:Nil];
// [self dismissModalViewControllerAnimated:NO];
}
For iOS8 (Also I have an embedded video that is not a youtube video) the only solution I could get to work was to catch either one of viewWill/DidLayoutSubviews, and as an added bonus you don't need to change the HTML or use any private APIs :
So basically:
#property (nonatomic) BOOL showingVideoFromWebView;
...
...
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeOther) {
//Was "other" in my case... Might be UIWebViewNavigationTypeLinkClicked
self.showingVideoFromWebView = YES;
}
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
// Do whatever...
// Note: This will get called both when video is entering fullscreen AND exiting!
self.showingVideoFromWebView = NO;
}
In my case my web view is inside a UITableViewCell so I had to find a way to communicate between the cell and the view controller, and to also avoid using a BOOL flag I did this:
- (BOOL)webView:(UIWebView *)webView shouldStartLoad.....
... if (opening video check....) {
[[NSNotificationCenter defaultCenter] addObserverForName:#"webViewEmbedVidChangedState" object:nil queue:nil usingBlock:^(NSNotification *note) {
// Do whatever need to be done when the video is either
// entering fullscreen or exiting fullscreen....
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"webViewEmbedVidChangedState" object:nil];
}];
}
- (void)viewWillLayoutSubviews.....
[[NSNotificationCenter defaultCenter] postNotificationName:#"webViewEmbedVidChangedState" object:nil];
Actually for the reverse engineering purposes you can also use Cocoa API
like
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleNotification:)
name:nil
object:nil];
In this case you will receive all notifications
I have a single view app with 5 buttons and when one of the buttons is pressed, the player slides up over the original view and begins playing the video in fullscreen (as it should).
All works great with the exception of when pressing the Fullscreen/Minimize icon (the two diagonal arrows pointing to each other next to the play back controls). When pressing this, the original view with the five buttons slides up over the video player. The problem is the video is still playing underneath the original view. I would really like to eliminate the Fullscreen/Minimize icon but from I can tell, that does not seem possible. So... I am thinking, I might be able to use an observer to listen to when the Fullscreen/Minimize icon is pressed and I can do what I need to. I just can not find anything solid on how to do this. Any help/direction would be greatly appreciated.
Here is my current code...
-(IBAction)playvideo {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Megamind" ofType:#"mov"]];
MPMoviePlayerViewController * playerController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:(MPMoviePlayerViewController *)playerController];
playerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playerController.moviePlayer play];
[playerController release];
playerController=nil;
}
- (void)moviePlayerWillExitFullscreen:(NSNotification *)theNotification {
MPMoviePlayerController *playerController = [theNotification object];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerWillExitFullscreen:)
name:MPMoviePlayerWillExitFullscreenNotification
object:nil];
[playerController stop];
[self dismissMoviePlayerViewControllerAnimated];
}
This line is causing you that behaviour.
[self presentMoviePlayerViewControllerAnimated:(MPMoviePlayerViewController *)playerController];
It is pretty much similar to your regular presentModalViewController method.
It presents the Movieplayer and its view controller Modally. So the default settings here are
movieplayer.controlStyle = MPMovieControlStyleFullScreen
which are set up by default.
So when you press those diagonal arrows, it exits that mode, and gives a notification for that. But you have to setup an observer first to listen to that notifcation as you did for movie finished.
You did
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieFinishedPlayback:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
This adds a notification to observe for movie completion notifications.
For exiting full screen mode add one more observer that is this..
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieExitFullScreen:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
And you should be good to go after adding the -(void) movieExitFullScreen:(NSNotification *) selector for the same. Hope it helps. :)
Put this line just after the init of your MPMoviePlayer :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerWillExitFullscreen:)
name:MPMoviePlayerWillExitFullscreenNotification
object:nil];
I think you're adding the observer in the method where you want to be REMOVING it.
You want this
MPMoviePlayerController *playerController = [theNotification object];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerWillExitFullscreen:)
name:MPMoviePlayerWillExitFullscreenNotification
object:nil];
in the playVideo()
and THIS
[[NSNotificationCenter defaultCenter] removeObserver:self
name:name:MPMoviePlayerWillExitFullscreenNotificationn
object:nil];
in the moviePlayerWillExitFullscreen method.
I did find a solution and my lack of knowledge put me in a situation where I do not fully understand why it works this way. My apologies for not having a thorough reasoning. In my original code... the MPMoviePlayerWillExitFullscreenNotification was not answering to taps. This is true for MPMoviePlayerDidExitFullscreenNotification as well. What was answering was MPMoviePlayerPlaybackDidFinishNotification. Here is teh working code in knowing that the MPMoviePlayerPlaybackDidFinishNotification was working and also applied to the Fullscreen/Embed presses.
-(IBAction)playvideo {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Megamind" ofType:#"mov"]];
MPMoviePlayerViewController * playerController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieFinishedPlayback:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self presentMoviePlayerViewControllerAnimated:(MPMoviePlayerViewController *)playerController];
playerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playerController.moviePlayer play];
[playerController release];
playerController=nil;
NSLog(#"playvideo");
}
- (void)movieFinishedPlayback:(NSNotification*)notification {
MPMoviePlayerController *playerController = [notification object];
[playerController pause];
[self dismissMoviePlayerViewControllerAnimated];
}