Fawaz
Fawaz

Reputation: 602

Get The AVPlayer instance from AppDelegate

Im trying to Playing Audio from a Video Asset in the Background As Apple mentioned in the following example Apple example

We need to set the AVPlayer to nil so that the app continue playing the audio in the background .

enter image description here

the problem is how to get the AVPlayer instance from AppDelegate I tried this method but nothing work and the app crash when I Enter the Background

- (void)applicationDidEnterBackground:(UIApplication *)application {
    Player *PlayerViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    PlayerViewController.VideoPlayer = nil;
}

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Home setVideoPlayer:]: unrecognized selector sent to instance 0x104835000'

also I tried this and its not wokring

- (void)applicationDidEnterBackground:(UIApplication *)application {
    Player *PlayerViewController ;
    PlayerViewController.VideoPlayer = nil;    
}

Upvotes: 0

Views: 101

Answers (1)

Fawaz
Fawaz

Reputation: 602

I found the answer

we need to controll applicationDidEnterBackground and applicationDidEnterBackground in the same Player UIViewController class by adding this 2

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disconnectAVPlayer) name:UIApplicationDidEnterBackgroundNotification  object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reconnectAVPlayer) name:UIApplicationWillEnterForegroundNotification  object:nil];

then we can set VideoPlayer to nil like this

- (void)disconnectAVPlayer{
    self.playerLayer.player = nil;
}

- (void)reconnectAVPlayer{
    self.playerLayer.player = self.VideoPlayer;    
}

NOTE : We need to set AVPlayerLayer to nil not the actual AVPlayer

Upvotes: 1

Related Questions