Question

I've used this method How do I get my AVPlayer to play while app is in background? to have an AVPlayer play in the background so the user can listen while browsing safari etc. Only problem is now AVPlayer continues to play when there is an incoming call and stays playing during the call. Is there a way to catch the incoming call and end call events so AVPlayer can be stopped and started manually?

Was it helpful?

Solution

Through coreTelephony framework we have to find or detect the incoming call. From there you have to initiate your local notification to stop your AVPlayer. after importing do like this

     CTCallCenter * _callCenter = [[CTCallCenter alloc] init];
    _callCenter.callEventHandler = ^(CTCall* call)
    {

        if ([call.callState isEqualToString:CTCallStateDisconnected])
        {
            NSLog(@"Call has been disconnected");
        }
        else if([call.callState isEqualToString:CTCallStateDialing])
        {
            NSLog(@"Call start");
        }
        else if ([call.callState isEqualToString:CTCallStateConnected])
        {

          NSLog(@"Call has just been connected");
        }
        else if([call.callState isEqualToString:CTCallStateIncoming])
        {
            NSLog(@"Call is incoming");
            // You have to initiate/post your local notification through NSNotification center like this 
        [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAVPlayer" object:nil];
        } else
        {
            NSLog(@"None of the conditions");
        }


    };

Refer this :https://developer.apple.com/library/ios/navigation/#section=Frameworks&topic=CoreTelephony

OTHER TIPS

You could use the CallKit for getting phone call event now. (iOS 10.0+) This is good for me.

#import <CallKit/CallKit.h>

@interface ViewController ()<CXCallObserverDelegate> {
    CXCallObserver *_center;
}

-(void)viewDidLoad

_center = [[CXCallObserver alloc] init];
dispatch_queue_t queue = dispatch_queue_create("THIS_IS_A_CALL",NULL);
[_center setDelegate:self queue:queue];

Delegate

- (void)callObserver:(CXCallObserver *)callObserver callChanged:(CXCall *)call {

    NSString *tag = @"callObserver";
    NSString *content = @"";

    if (call.isOutgoing) {
        content = @"call.isOutgoing";
    }
    if (call.hasEnded) {
        content = @"call.hasEnded";
    }

    if (call.hasConnected) {
        content = @"call.hasConnected";
    }

    if (call.isOnHold) {
        content = @"call.isOnHold";
    }
    NSLog(@"%@ - %@", tag, content);
}

More detail: https://developer.apple.com/documentation/callkit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top