In my iPhone application I want to keep play video when application enter in background mode.
I am using AVPlayer and not finding any way to play video in background. I will be very grateful if any one can help me in this. Thanks
In my iPhone application I want to keep play video when application enter in background mode.
I am using AVPlayer and not finding any way to play video in background. I will be very grateful if any one can help me in this. Thanks
With surprise I can say that this can be achieved and I just did it.
This method supports all the possibilities:
As long as you have an instance of
AVPlayer
running iOS prevents auto lock of the device.First you need to configure the application to support audio background from the Info.plist file adding in the
UIBackgroundModes
array theaudio
element.Then put in your AppDelegate.m into
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
these methods
and
#import <AVFoundation/AVFoundation.h>
Then in your view controller that controls
AVPlayer
and
then respond to the
Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).
When you control the reproduction of the video (I have
play:
andpause:
methods) setand
and the corresponding method to be invoked that will launch a timer and resume the reproduction.
You can do this background task when application is in background :
1> audio
2> location
3> voip
4> newsstand-content
5> external-accessory
6> bluetooth-central
7> bluetooth-peripheral
see this link,
also this may help you: AVPlayer play video in background
You can achive your requirement by using below sets of below code.
Swift: 4.2
Just, Create subclass of
UIViewController
Now, Almoast done. Just create
UIViewcontroller
class by using sub-class as below.The above answers pause the video for a second when the app enters background, but by using the method mentioned below it keeps the video playing while app goes to background without any glitch.
If the AVPlayer's current item is displaying video on the device's display, playback of the AVPlayer is automatically paused when the app is sent to the background. There are two ways to prevent this pause:
Try this code in your
applicationDidEnterBackground
:i found it somewhere on the stack works for me
Also check out this tutorial which covers background modes including background audio.. http://www.raywenderlich.com/29948/backgrounding-for-ios