Open calendar from Swift app - swift

How can I open a calendar from Swift app (when pressing a button for example)? Or is there a way to embed a calendar in a view controller in the app?
I want to avoid using external calendars programmed by others. Thanks!

You can open the Calendar app by using the url scheme calshow://:
Swift 3+
guard let url = URL(string: "calshow://") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
Swift 2 and below
UIApplication.sharedApplication().openURL(NSURL(string: "calshow://")!)
With EventKit, you can implement your self a calendar. You should read Calendar and Reminders Programming Guide from Apple site.

openURL Deprecated in iOS10
From Apple’s guide to What’s New in iOS in the section on UIKit:
The new UIApplication method openURL:options:completionHandler:, which
is executed asynchronously and calls the specified completion handler
on the main queue (this method replaces openURL:).
Swift 3
func open(scheme: String) {
if let url = URL(string: scheme) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],
completionHandler: {
(success) in
print("Open \(scheme): \(success)")
})
} else {
let success = UIApplication.shared.openURL(url)
print("Open \(scheme): \(success)")
}
}
}
// Typical usage
open(scheme: "calshow://")
Objective-C
- (void)openScheme:(NSString *)scheme {
UIApplication *application = [UIApplication sharedApplication];
NSURL *URL = [NSURL URLWithString:scheme];
if ([application respondsToSelector:#selector(openURL:options:completionHandler:)]) {
[application openURL:URL options:#{}
completionHandler:^(BOOL success) {
NSLog(#"Open %#: %d",scheme,success);
}];
} else {
BOOL success = [application openURL:URL];
NSLog(#"Open %#: %d",scheme,success);
}
}
// Typical usage
[self openScheme:#"calshow://"];
Note:- Don't forgot to add privacy usage description in your info.plist file.,if you are trying to open any system app then in iOS 10+ you need to specify privacy usage description in your info.plist file else your app get crash.

As HoaParis already mentioned, you can call the calendar by using the openURL method.
There is no embedded calendar by apple by default but you could check out other calendars for example the open-source one CVCalendar which is available at github. So you could either use it in your project or check how the developer has coded the calendar.

Related

in Swift how to make a phone call with no confirmation dialog? [duplicate]

This question already has an answer here:
ios User Prompt when making outgoing call via URL Scheme 10.2+
(1 answer)
Closed 4 years ago.
for my company, I need my app to make periodically some phone call to a given number and then analyze call quality.
I'm testing
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
UIApplication.shared.openURL(phoneCallURL as URL)
}
}
}
}
but this code requires for a an "ok" on confirmation dialog. How can I avoid it? I found some answer, but they are old and in objective c
Taken from the iOS SDK Release Notes for iOS 10.3 https://developer.apple.com/library/archive/releasenotes/General/RN-iOSSDK-10.3/
openURL
When a third party application invokes openURL: on a tel://, facetime://, or facetime-audio:// URL, iOS displays a prompt and requires user confirmation before dialing.

How can I open the parent app on iPhone from my WatchKit app with watchos 2? [duplicate]

I know that the openParentApplication api in watch kit extension can open the host app in the background but not in the foreground.
I also tried using openUrl() api of NSExtensionContext as below:
NSExtensionContext *ctx = [[NSExtensionContext alloc] init];
NSURL *url = [NSURL URLWithString:#"myScheme://today"];
[ctx openURL:url completionHandler:^(BOOL success) {
NSLog(#"fun=%s after completion. success=%d", __func__, success);
}];
[ctx completeRequestReturningItems:ctx.inputItems completionHandler:nil];
Here too the host app is not launched. Am I missing something? or is it not possible to
launch the host app from watch kit extension?
As of Beta 3 of iOS 8.2 it is currently not possible to open iOS app to foreground.
As you said openParentApplication can open app in background. Unfortunately there is no sign of API to open app on iPhone.
Multiple posts on Apple Dev Forums mentioned that it's not possible
https://devforums.apple.com/message/1076125#1076125
Correct, a notification can still declare a background action that the iPhone app will handle, so in that sense it can launch the iPhone app. But the iPhone app cannot be brought to the foreground by a WatchKit app.
And other post
https://devforums.apple.com/message/1082620#1082620
On a device, it[Watch app] will not - bring your iOS app to the foreground.
I'm hopeful that Apple will provide API for launching the parent app from a watch app in a future beta, but for now I've managed to achieve it by doing the following...
Call openParentApplication:reply: as normal:
- (void)openPhoneApp {
[WKInterfaceController openParentApplication:[NSDictionary new] reply:nil];
}
Implement application:handleWatchKitExtensionRequest:reply: in your AppDelegate, and launch itself using a custom URL scheme:
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"myappscheme://open"]];
}
If you need to open your parent app in the foreground, use Handoff!
https://developer.apple.com/handoff/
Example:
Somewhere shared for both:
static let sharedUserActivityType = "com.yourcompany.yourapp.youraction"
static let sharedIdentifierKey = "identifier"
on your Watch:
updateUserActivity(sharedUserActivityType, userInfo: [sharedIdentifierKey : 123456], webpageURL: nil)
on your iPhone in App Delegate:
func application(application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
if (userActivityType == sharedUserActivityType) {
return true
}
return false
}
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]!) -> Void) -> Bool {
if (userActivity.activityType == sharedUserActivityType) {
if let userInfo = userActivity.userInfo as? [String : AnyObject] {
if let identifier = userInfo[sharedIdentifierKey] as? Int {
//Do something
let alert = UIAlertView(title: "Handoff", message: "Handoff has been triggered for identifier \(identifier)" , delegate: nil, cancelButtonTitle: "Thanks for the info!")
alert.show()
return true
}
}
}
return false
}
And finally (this step is important!!!): In your Info.plist(s)

How can I open the parent app on iPhone from my WatchKit app?

I'm trying to open the parent application of my Apple Watch app.
In Xcode Beta 2 we could use this code:
WKInterFaceController.openParentApplication
However, in Xcode beta 3 I couldn't found that code any longer. Now I don't know how to open the parent application from the watch app. Please help.
The Objective-C method is:
+ (BOOL)openParentApplication:(NSDictionary *)userInfo
reply:(void (^)(NSDictionary *replyInfo,
NSError *error))reply
The Swift method is:
class func openParentApplication(_ userInfo: [NSObject : AnyObject]!,
reply reply: (([NSObject : AnyObject]!,
NSError!) -> Void)!) -> Bool
So you need to pass the iPhone application a reply() block in order to have activate it from your WatchKit extension. Here's one way it could be implemented, for instance:
NSString *requestString = [NSString stringWithFormat:#"executeMethodA"]; // This string is arbitrary, just must match here and at the iPhone side of the implementation.
NSDictionary *applicationData = [[NSDictionary alloc] initWithObjects:#[requestString] forKeys:#[#"theRequestString"]];
[WKInterfaceController openParentApplication:applicationData reply:^(NSDictionary *replyInfo, NSError *error) {
NSLog(#"\nReply info: %#\nError: %#",replyInfo, error);
}];
Your iPhone application's AppDelegate needs to implement the following method:
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {
NSString * request = [userInfo objectForKey:#"requestString"];
if ([request isEqualToString:#"executeMethodA"]) {
// Do whatever you want to do when sent the message. For instance...
[self executeMethodABC];
}
// This is just an example of what you could return. The one requirement is
// you do have to execute the reply block, even if it is just to 'reply(nil)'.
// All of the objects in the dictionary [must be serializable to a property list file][3].
// If necessary, you can covert other objects to NSData blobs first.
NSArray * objects = [[NSArray alloc] initWithObjects:myObjectA, myObjectB, myObjectC, nil];
NSArray * keys = [[NSArray alloc] initWithObjects:#"objectAName", #"objectBName", #"objectCName", nil];
NSDictionary * replyContent = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
reply(replyContent);
}
The WKInterfaceController method openParentApplication:reply: launches the containing app in the background when the iPhone (or iOS Simulator) is unlocked or locked. Note that statements from Apple indicate that the WatchKit extension was always intended to launch your iPhone application in the background, and it was only an implementation detail of the simulator that it appeared to launch your iPhone application in the foreground in previous betas.
If you want to test your WatchKit app and your iPhone app running at the same time, simply launch the WatchKit app from Xcode under the Schemes menu, and then manually launch your iPhone app in the simulator by clicking on its springboard icon.
If you need to open your parent app in the foreground, use Handoff!
Example:
Somewhere shared for both:
static let sharedUserActivityType = "com.yourcompany.yourapp.youraction"
static let sharedIdentifierKey = "identifier"
on your Watch:
updateUserActivity(sharedUserActivityType, userInfo: [sharedIdentifierKey : 123456], webpageURL: nil)
on your iPhone in App Delegate:
func application(application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
if (userActivityType == sharedUserActivityType) {
return true
}
return false
}
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]!) -> Void) -> Bool {
if (userActivity.activityType == sharedUserActivityType) {
if let userInfo = userActivity.userInfo as? [String : AnyObject] {
if let identifier = userInfo[sharedIdentifierKey] as? Int {
//Do something
let alert = UIAlertView(title: "Handoff", message: "Handoff has been triggered for identifier \(identifier)" , delegate: nil, cancelButtonTitle: "Thanks for the info!")
alert.show()
return true
}
}
}
return false
}
And finally (this step is important!!!): In your Info.plist(s)

How to use openURL for making a phone call in Swift?

I have converted the code for making a phone call from Objective-C to Swift, but in Objective-C, we can set the type of the URL that we like to open (e.g. telephone, SMS, web) like this:
#"tel:xx"
#"mailto:info#example.es"
#"http://stackoverflow.com"
#"sms:768number"
The code in Swift is:
UIApplication.sharedApplication().openURL(NSURL(string : "9809088798")
I read that have not released any scheme parameter for tel:, but I don't know if Swift can detect if the string is for making a phone call, sending email, or opening a website. Or may I write:
(string : "tel//:9809088798")
?
I am pretty sure you want:
UIApplication.sharedApplication().openURL(NSURL(string: "tel://9809088798")!)
(note that in your question text, you put tel//:, not tel://).
NSURL's string init expects a well-formed URL. It will not turn a bunch of numbers into a telephone number. You sometimes see phone-number detection in UIWebView, but that's being done at a higher level than NSURL.
EDIT: Added ! per comment below
A self-contained solution in Swift:
private func callNumber(phoneNumber:String) {
if let phoneCallURL:NSURL = NSURL(string:"tel://\(phoneNumber)") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL(phoneCallURL)) {
application.openURL(phoneCallURL);
}
}
}
Now, you should be able to use callNumber("7178881234") to make a call.
For Swift in iOS:
var url:NSURL? = NSURL(string: "tel://9809088798")
UIApplication.sharedApplication().openURL(url!)
You need to remember to remove the whitespaces or it won't work:
if let telephoneURL = NSURL(string: "telprompt://\(phoneNumber.stringByReplacingOccurrencesOfString(" ", withString: ""))") {
UIApplication.sharedApplication().openURL(telelphoneURL)
}
"telprompt://" will prompt the user to call or cancel while "tel://" will call directly.
# confile:
The problem is that your solution does not return to the app after the
phone call has been finished on iOS7. – Jun 19 at 13:50
&# Zorayr
Hm, curious if there is a solution that does do that.. might be a
restriction on iOS.
use
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://9809088798")!)
You will get a prompt to Call/Cancel but it returns to your application. AFAIK there is no way to return (without prompting)
You must insert "+"\ is another way
private func callNumber(phoneNumber:String) {
if let phoneCallURL:NSURL = NSURL(string:"tel://"+"\(phoneNumber)") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL(phoneCallURL)) {
application.openURL(phoneCallURL);
}
}
}
Small update to Swift 3
UIApplication.shared.openURL(NSURL(string: "telprompt://9809088798")! as URL)
The following code snippet can tell if the SIM is there or not and if the device is capable of making the call and if ok then it'll make the call
var info = CTTelephonyNetworkInfo()
var carrier = info.subscriberCellularProvider
if carrier != nil && carrier.mobileNetworkCode == nil || carrier.mobileNetworkCode.isEqual("") {
//SIM is not there in the phone
}
else if UIApplication.sharedApplication().canopenURL(NSURL(string: "tel://9809088798")!)
{
UIApplication.sharedApplication().openURL(NSURL(string: "tel://9809088798")!)
}
else
{
//Device does not have call making capability
}
For making a call in swift 5.1, just use the following code: (I have tested it in Xcode 11)
let phone = "1234567890"
if let callUrl = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(callUrl) {
UIApplication.shared.open(callUrl)
}
Edit:
For Xcode 12.4, swift 5.3, just use the following:
UIApplication.shared.open(NSURL(string: "tel://555-123-1234")! as URL)
Make sure that you import UIKit, or it will say that it cannot find UIApplication in scope.
For swift 3
if let phoneCallURL:URL = URL(string:"tel://\(phoneNumber ?? "")") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
application.open(phoneCallURL, options: [:], completionHandler: nil);
}
}
For swift 4:
func call(phoneNumber: String) {
if let url = URL(string: phoneNumber) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],
completionHandler: {
(success) in
print("Open \(phoneNumber): \(success)")
})
} else {
let success = UIApplication.shared.openURL(url)
print("Open \(phoneNumber): \(success)")
}
}
}
Then, use the function:
let phoneNumber = "tel://+132342424"
call(phoneNumber: phoneNumber)
Swift 4 and above
let dialer = URL(string: "tel://5028493750")
if let dialerURL = dialer {
UIApplication.shared.open(dialerURL)
}
I prefer deferring the URL creation to the built-ins like:
var components = URLComponents()
components.scheme = "tel"
components.path = "1234567890"
print(components.url!) //Prints out: "tel:1234567890"
Which can then be used in UIApplication.shared.openURL

How do I get my AVPlayer to play while app is in background?

I've done my homework... been reading here, the docs, googling, stackoverflowing... but still no luck in making my sound stick when the user makes the app go into the background.
What I have done so far:
Added the UIBackgroundModes, audio to the plist-file.
First this code:
radioAudio = [[AVAudioSession alloc] init];
[radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil];
[radioAudio setActive:YES error:nil];
Then this:
NSString *radioURL = #"http://xxx.xxx.xxx/radio.m3u";
radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain];
But as soon as the user hits the home-button, my sound dies.
I also found this, but not added yet cuase some stuff I've read says it is not needed;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
[[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
bgTaskId = newTaskId;
Right now I have no idea where I should go to make my AVPlayer let the radio sing while the user does other stuff on the phone.
I am testing this on an iPhone 4 with 4.2. Building it for 4.0.
Anyone have any suggestions what I should do?
UPDATE IOS 11.2 with Swift 4:
Now if you are using AVPlayer to play music files you should also configure MPNowPlayingInfoCenter.default() to show now playing info on the lock screen.
Below code will show now playing controls on the screen but it won't be able to respond any commands.
If you also want to controls to work you should check apple's sample project here: https://developer.apple.com/library/content/samplecode/MPRemoteCommandSample/Introduction/Intro.html#//apple_ref/doc/uid/TP40017322
Apple sample code covers all but i find it confusing.
If you want to play sound and show controls on the lock screen these steps will do just fine.
IMPORTANT NOTE: If you are NOT using AVPlayer to play sound. If you are using some third party libraries to generate sound or playback a sound file you should read comments inside the code. Also if you are using ios simulator 11.2 you won't be able to see any controls on lock screen. You should use a device to see it work.
1- Select project -> capabilites -> set background modes ON -> tick Audio, AirPlay and Picture in Picture
2- AppDelegate.swift file should look like this :
import UIKit
import AVFoundation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
// Override point for customization after application launch.
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
//!! IMPORTANT !!
/*
If you're using 3rd party libraries to play sound or generate sound you should
set sample rate manually here.
Otherwise you wont be able to hear any sound when you lock screen
*/
//try AVAudioSession.sharedInstance().setPreferredSampleRate(4096)
}
catch
{
print(error)
}
// This will enable to show nowplaying controls on lock screen
application.beginReceivingRemoteControlEvents()
return true
}
}
3- ViewController.swift should look like this:
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController
{
var player : AVPlayer = AVPlayer()
override func viewDidLoad()
{
super.viewDidLoad()
let path = Bundle.main.path(forResource: "music", ofType: "mp3")
let url = URL(fileURLWithPath: path!)
// !! IMPORTANT !!
/*
If you are using 3rd party libraries to play sound
or generate sound you should always setNowPlayingInfo
before you create your player object.
right:
self.setNowPlayingInfo()
let notAVPlayer = SomePlayer()
wrong(You won't be able to see any controls on lock screen.):
let notAVPlayer = SomePlayer()
self.setNowPlayingInfo()
*/
self.setNowPlayingInfo()
self.player = AVPlayer(url: url)
}
func setNowPlayingInfo()
{
let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]()
let title = "title"
let album = "album"
let artworkData = Data()
let image = UIImage(data: artworkData) ?? UIImage()
let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_) -> UIImage in
return image
})
nowPlayingInfo[MPMediaItemPropertyTitle] = title
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = album
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
}
#IBAction func startPlayingButtonPressed(_ sender: Any)
{
self.player.play()
}
OLD ANSWER IOS 8.2:
Patrick's answer is totally right.
But i'm gonna write what i do for ios 8.2:
I add my app's info.plist
required background modes
like below:
And in my AppDelegate.h i add these imports:
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
Then in my AppDelegate.m i wrote application didFinishLaunchingWithOptionsthis exactly like below:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
return YES;
}
Now App keeps playing music even if screen is locked :)
Had the same problem, but found a solution for this..
Look here: https://devforums.apple.com/message/395049#395049
The content of the above link:
Replace APPNAME with your own app name!
Im on iOS 4.2.1
EDIT: Working with iOS5 + 6 + 7 beta so far
Add UIBackgroundModes in the APPNAME-Info.plist, with the selection App plays audio
Then add the AudioToolBox framework to the folder frameworks.
In the APPNAMEAppDelegate.h add:
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
so it look like this:
...
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
...
In the APPNAMEAppDelegate.m add the following:
// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
/* Pick any one of them */
// 1. Overriding the output audio route
//UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
//AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
// 2. Changing the default output audio route
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
into the
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
but before the two lines:
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
Build your project and see if theres any error, If not, try debug on Device insted of the Simulator, it CAN bug on simulator.
Hope this helps others with same problem..
I have successfully made audio run in the background by adding the following to my applicationDidFinishLaunching
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
iOS 9 Swift
All you should need is add the following to your didFinishLaunchingWithOptions
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
//TODO
}
You have a good example of a GPS background app that plays sounds even when in background :
http://www.informit.com/articles/article.aspx?p=1646438&seqNum=5
In this example, AudioToolbox is used.
I did a test myself and it works : create a simple project that monitors the GPS post (UIBackgroundModes location) , and every x received position, play a sound using
AudioServicesPlaySystemSound(soundId);
Then if you put audio as part of your UIBackgroundModes and the sounds will be played, even if the application isn't in foreground anymore.
I've made such a test and it works ok !
(I didn't manage to get it working with AVPlayer so I fallbacked to AudioToolbox)
I've the same problem and I found solution in Apple Docs:https://developer.apple.com/library/ios/qa/qa1668/_index.html
Q: How do I ensure my media will continue playing when using AV Foundation while my application is in the background?
A: You must declare your app plays audible content while in the background, and assign an appropriate category to your audio session. See also Special Considerations for Video Media.
Working for Swift 5
Here are the 4 things that I did for my music to play in the background from a video that the avPlayer was playing. I followed the Apple directions link from #AndriySavran's answer and this Apple link plus a few other things.
1- In AppDelegate's didFinishLaunching I put:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try AVAudioSession.sharedInstance().setCategory( .playback, mode: .moviePlayback, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
// whatever other code that you use ...
return true
}
2- Follow this answer from #LeoDabus. In your Signing & Capabilties > Background Modes (if background modes isn't there then select it from Capabilites then) > tick Audio, Airplay, and Picture in Picture
3- In the view controller that has your AVPlayer, add the .didEnterBackgroundNotification and .willEnterForegroundNotification notifications
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(appDidEnterBackground),
name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(appWillEnterForeground),
name: UIApplication.willEnterForegroundNotification, object: nil)
}
4- for the selector method add the code from the Apple link
#objc func appDidEnterBackground() {
playerLayer?.player = nil
}
#objc func appWillEnterForeground() {
playerLayer?.player = self.player
}