DEVELOPING APPS NATIVELY PAYS OFF GREATLY
Enabling the Fancy iOS Picture In Picture Video Player on Xamarin
Picture In Picture (PIP) was introduced years ago in iOS 9, but it was only available for iPads. It was brought to iPhones recently in iOS 14, so I wanted to implement it in my app. The iOS 9 documents showed that several steps were involved to implement this, and I was having a hard time integrating that with Xamarin Forms. However, while I was experimenting I realized, Apple made changes to simplify PIP implementation greatly, so those steps are not needed anymore. This article assumes that you already followed Microsoft’s Xamarin Video Player tutorial, to implement a simple iOS video player in your app, and only goes over the steps to enable PIP.
- Add the snippet below to your
returnstatement. Make sure that you use the right
AVAudioSessionCategorybecause the PIP controller disappears depending on the category:
var audioSession = AVAudioSession.SharedInstance();
NSError nSError = new NSError();
audioSession.SetActive(true, AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation, out nSError);
2. And then go to your Info.plist and in the application tab, Enable Background Modes and check the Picture in Picture mode, and that shall automatically add the required key to your Source tab.
Et puts voilà! After you implement these 2 short steps, just build your app onto your phone, play your video and then press the Home button. Your video will transform into the fancy PIP view! You can also test this using the sample GitHub repo I created.
This section is for people curious about the behavior, but they would rather not clone and build the sample. There’s a few points to note about the behavior:
- If the video is playing in the app, you just need to press the home button and it will start. You do not need to tap on the PIP button.
- Once playing in the background, you can simply hide the video temporarily by swiping it to the right and it will show an arrow on the screen
- There’s only a few default places on the screen you can pin the video to keep playing from which you can’t change.
- You can also launch PIP within the app by tapping the PIP icon on the top left of the video controls that automatically is displayed by iOS.
- This works since we are using a non-customized AVPlayer for our video, so it may not work with other video libraries.
- Video calls with PIP use private API, only available for FaceTime.