AVPlayer Audio Lock Screen updates stop working, only after another AVPlayer instance plays Video content - swift

Summary:
If you only use AVPlayer to play streaming audio only in your application, then Lock Screen Updates will work just fine (many streams - one after another). However, if you use AVPlayer to play both Streaming Audio followed by a Local Video file (even while using separate instances of AVPlayer and on different view controllers), then when you try to play Streaming Audio again - nothing will show up on the Lock Screen any more. Not related to cleanup - because playing only multiple audio files in a row works fine and shows up on the Lock Screen every time, but as soon as you play 1 video file (Or even initialize it to any AVPlayer without calling .play() on it), audio Lock Screen updates permanently stop working, and you need to restart the app for it to work again. It sounds like an AVFoundation bug to me...
Detailed Breakdown:
I have an appliction with View Controllers A and B. View controller A is the presenter of view controller B (pushes it using a navigation controller). Both A and B have a seperate AVPlayer inside them (A's plays audio. B's plays video. Audio is streamed. Video is local file in docs directory).
VC A configures its AVPlayer to update the Lock Screen with the Artwork Image, progress status, forward 15s, back 15s buttons. Everything works great if only view controller A's player is used to play audio - no matter how many times I go back and forward to it (I.E. VC B's player is never used to play()). (The whole controller gets deinit correctly) The Lock Screen always works, and always updates all required playback information.
VC A (AVPlayer1) --> PUSH --> VC B (AVPlayer2)
This is the code to register for Lock Screen updates (including button and progress callbacks):
func setupNowPlaying() {
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = title
nowPlayingInfo[MPMediaItemPropertyArtist] = artist
let artwork = MPMediaItemArtwork.init(boundsSize: self.artImage.size, requestHandler: { (size) -> UIImage in
return self.artImage
})
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
guard let player = self.player else { return }
guard let currentItem = self.player?.currentItem else { return }
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = currentItem.asset.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = currentItem.currentTime().seconds
let rcc = MPRemoteCommandCenter.shared()
let skipBackwardCommand = rcc.skipBackwardCommand
skipBackwardCommand.isEnabled = true
skipBackwardCommand.addTarget(handler: skipBackward)
skipBackwardCommand.preferredIntervals = [15]
let skipForwardCommand = rcc.skipForwardCommand
skipForwardCommand.isEnabled = true
skipForwardCommand.addTarget(handler: skipForward)
skipForwardCommand.preferredIntervals = [15]
UIApplication.shared.beginReceivingRemoteControlEvents()
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
Additionally, the following is hooked up in AppDelegate (applicationWillResignActive), to enable background playback (standard stuff):
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay, .allowBluetooth, .allowBluetoothA2DP ])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
The problem of Not showing anything on the lock screen starts to occur when VC B gets presented and plays video using its own separate AVPlayer. VC A's AVPlayer is first paused. If I call .play() on VC B's player then when I come back to VC A (by clicking Back < in the nav bar), the progress updates to the Lock Screen will never show up again (the whole playback UI doesn't show up), however the background playback still works.
So as soon as I use another AVPlayer on another View Controller, my original player will never be able to post updates to the Lock Screen UI, ever again, until the application is terminated and re-launched.
I tried to do full cleanup and re-init on the player in VC A.
I tried to just not call .play() on VC B. (Everything works fine with VC A in that case).
VC B's player is not registered for Lock Screen updates, because it just plays video in the app for preview purposes.
Something under-the-hood with Apple's AVPlayer breaks VC A's AVPlayer's Lock Screen updates capability, as soon as another instance of AVPlayer is introduced and used to play in another View Controller.
I know the issue is related to the second AVPlayer on the separate controller, because just not calling .play() on VC B's player, fixes the screen lock update disappearance issue on VC A's player.
How can I work around this? I don't want to remove VC A's player from superview, and pass it to VC B, and reconfigure it, then reconfigure it back again in VC A if the user comes back. (very laborious and error prone). It also currently bricks Lock Screen updates permanently, after the first time the user goes through VC B's playback (which is part of my happy path)
Thanks in advance,
Alex

I was able to avoid this problem by removing dependence on AVPlayerViewController in VC-B. Now I use a third party component called: "Player" (Cocoapods: "Player"), which uses an AVPlayerLayer, but not AVPlayerViewController. https://cocoapods.org/pods/Player
Unfortunately I lost my playback UI controls (progress bar, play button, full screen button - which AVPlayerViewController was giving me for free). So I will have to build some custom playback controls.
So it seems that AVPlayerViewController was causing the problem with the lock screen and breaking it. After switching to using "Player", which still uses AVPlayer, but not AVPlayerViewController, the problem went away, and I now always see my playback controls on the Lock Screen.

Related

AppleTv - CustomOverlayViewController force popup at timecode

I'm using the CustomOverlayViewController on an AVPlayerViewController to display movies related to what the user is currently watching. (https://developer.apple.com/documentation/avkit/avplayerviewcontroller/3229856-customoverlayviewcontroller)
I want to bring that up into focus automatically when the credits start playing. I have a timecode in my metadata and can detect when that occurs. But, I can't find a way to force the view to popup without the user swiping to it on the remote. Is there a way to force this view into focus without user input?
P.S. It is fine if it can be accessed at other times manually by the user as well. I just need to be able to also autofocus it at a certain point.
I ran into the same issue and instead of using the customOverlayViewController property of AVPlayerViewController, I just call
vcToPresent = ViewController()
vcToPresent.modalPresentationStyle = .overCurrentContext
self.avPlayerVC?.present(vcToPresent, animated: true, completion: nil)
to present the desired VC on screen at the time you want it to display.

Dismissing SKScene Completely

Okay so I have an app that starts off with a menu view controller that prompts user to press one of 4ish buttons which then loads a viewcontroller which then presents a scene and the user plays the game based on which button was pressed.
I am then having the user being redirected to another viewcontroller which presents another another scene, once a condition is met (they lose the game). Only problem is, the 2nd viewcontroller(and i'm assuming it's scene) is still running. I know this because I have a print statement inside of it's override function update method to see if it's still there.
In addition, I have audio playing in my old gamesene and it's still currently playing. I wouldn't EXACTLY mind that since later on i'm going to just end up passing audio data (mute all) between all 3 viewcontrollers and their presented scenes.
Only problem with what is going on right now is that when I run the app since the old viewiewcontroller an it's scene seem to still be running underneath, it keeps calling the transition which causes a weird look where when the condition meets, the transition loops endlessly to the new viewcontroller then back to the beginning of the transition then to the new viewcontroller again.
I've tried this piece of code:
let theVC = self.viewController?.storyboard?.instantiateViewController(withIdentifier: "TrumpVC") as! TrumpViewController
self.viewController?.navigationController?.pushViewController(theVC, animated: true)
self.viewController?.dismiss(animated: true, completion: {});
But it doesn't seem to help at all :( Essentially I navigate to a new viewcontroller and dismiss the current one (this is all in my scene)
Thanks
Solution:
let theVC = self.viewController?.storyboard?.instantiateViewController(withIdentifier: "TrumpVC") as! TrumpViewController
self.viewController?.navigationController?.pushViewController(theVC, animated: true)
self.viewController?.removeFromParentViewController()
self.viewController?.dismiss(animated: true, completion: nil)
self.view?.presentScene(nil)

iPhone 4s 6.1.2 version UIViewcontroller gets refreshed on taking a image using camera

I've recorded an audio and then captured an image using my application's camera.
After that when I return to my view controller the recording data is reset or its refreshed. No recorded file exists.
Why does this issue happen only on iPhone 4s? Why does the view gets reset after using camera?
Because when you dismiss the ImagePickerController then your ViewWillAppear method will be called & All functionaly has been reset same as When view loads first time.
You need to save the functionality or check the condition on viewWillAppear method.
YOu can also set the fiunctionality on Cancelbutton press Or ImagePicker is dismiiss delegate method of ImagePicker to save the functionlity.

Multiple AVPlayers with AVPlayerLayers disappears second time push viewcontroller

I have a viewcontroller with four (4) AVPlayers (with AVPlayerLayers like APPLE example).
If I pop this viewcontroller and the push a new instance of the same type. I'm not able to play video in one or two AVPlayers. No errors and code runs fine, AVPlayerLayers also says it has a superLayer.
And to the most strange thing if I push home button, coming back to springboard and the enter the app all video players like magic start playing. It's like it rerender the view tree or something.
Any hints or clues?
PS. I wait for assets to be ready using loadValuesAsynchronouslyForKeys.
We had a similar problem. Following answer lead to the solution:
AVplayer not showing in ScrollView after 2-3 times
You have to call: [AVPlayer replaceCurrentItemWithPlayerItem:nil]; when your viewcontroller gets unloaded. This might be tricky as you might have added an observer or used addBoundaryTimeObserverForTimes:queue:usingBlock:
Also you have to be careful when checking agaings superlayer: Better check against uiview.window when determing whether your view is still attached to the view hierarchy.
yours
phil

MPMoviePlayerController inside UITabBarController

Ok, so here's the thing. I have a UIViewController that contains a UITabBarController. That tab bar has a UIViewController for each tab button. Now, inside one of the tab buttons is an MPMoviePlayerController that is playing a stream from over the network. Playing the stream works just fine and you can see the video and hear the audio.
The problem is when you navigate to another tab. The audio still plays, which is good, but when you go back to the stream, the video is black. The audio is still playing, but the video needs to be playing too.
Has anyone run into this problem before?
I'm currently using iOS 4.0 to build against and an iPhone 3GS.
If more information is needed, just ask and I'll do my best to answer.
Thanks,
Robbie
Strange things might happen if the view isn't on-screen (I believe it's removed from the view hierarchy when you switch tabs).
Have you tried using MPMoviePlayer's view directly? (not MPMoviePlayerController)
Can you add and remove the view and keep the movie playing?
Does pausing and resuming help?
Could you pass the view around between view controllers, or maybe make it a direct subview of the window in viewWillDisappear and move it back in viewDidAppear? (I'm not sure if the view's been removed from the hierarchy in viewWillAppear/viewDidDisappear.)
The solution I'm going ahead with is entering fullscreen mode and exiting fullscreen mode very quickly. It may not be the best thing, but it's working.
This still happens on iOS 6. If I have two movie player (one on each tab), even if they are not playing, if I switch form the first to the seconds tab and return to the first, the movie player will be black.
My solution was as simple as calling prepareToPlay on -viewDidAppear::
- (void)viewDidAppear:(BOOL)animated;
{
[super viewDidAppear:animated];
[self.moviePlayer prepareToPlay];
}
I believe this will add the shared internal view of MPMoviePlayerController to the view hierarchy.