无法在iOS中开始接收远程控制事件

Nik*_*rov 8 background objective-c remote-control avaudioplayer ios

在我的应用程序中,我希望让用户在后台控制音频播放.我在.plist中设置了backGround模式,在bg中播放就像我想要的那样.但是我无法通过触摸控制按钮得到任何响应.

我设置了AudioSession这样的

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance]setActive:YES error:nil];
Run Code Online (Sandbox Code Playgroud)

然后,在我放置播放器的viewContoller中,我beginReceivingRemoteControlEvents喜欢这个

 if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
    [self becomeFirstResponder];
    NSLog(@"Responds!");
}
Run Code Online (Sandbox Code Playgroud)

它打印出来 Responds!

但问题是这种方法永远不会被调用

    - (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    NSLog(@"Where is my event?");
    if(event.type == UIEventTypeRemoteControl)
    {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                NSLog(@"Pause");
                [self playWords:playButton];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"Next");
                [self next];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"Prev");
                [self prev];
                break;

        }
    }
Run Code Online (Sandbox Code Playgroud)

我甚至尝试写一个类别UIApplication让它成为第一个响应者,但它没有帮助

@implementation UIApplication (RemoteEvents)
-(BOOL)canBecomeFirstResponder
{
    return YES;
}
@end
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

解决方案 这就解决了我的问题在iOS4上输入背景来播放音频

Kha*_*man 13

我在我的项目中做了同样的工作,它工作正常.请按照这个,也许它会帮助你.更改事件名称等.在我的代码中_audio是AVAudioPlayer的对象.

- (void)viewDidLoad {
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
}

- (void)viewWillAppear {

      [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}


- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
            [_audio play];
            break;
        case UIEventSubtypeRemoteControlPause:
            [_audio pause];
            break;
        default:
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一旦我添加了 - (BOOL)canBecomeFirstResponder {return YES;},这对我有用.谢谢! (2认同)