Swift。接收远程控制事件以与 MPNowPLayingInfoCenter 配合使用

Swift. Receive remote control events to work with MPNowPLayingInfoCenter

据我了解,为了在锁定屏幕上显示音乐播放器,仅编写以下代码是不够的。

override func viewDidAppear(animated: Bool) {    
var mpic = MPNowPlayingInfoCenter.defaultCenter()
    mpic.nowPlayingInfo = [
        MPMediaItemPropertyTitle:"This Is a Test",
        MPMediaItemPropertyArtist:"Matt Neuburg"
    ]
}

我的应用程序也应该能够接收 remote control events

那么,如何在 Swift 中做到这一点?

我从 Apple Documentation 找到了这个,但它是给 Objective-C 的。

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // Turn on remote control event delivery
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    // Set itself as the first responder
    [self becomeFirstResponder];
}


- (void)viewWillDisappear:(BOOL)animated {

    // Turn off remote control event delivery
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];

    // Resign as first responder
    [self resignFirstResponder];

    [super viewWillDisappear:animated];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {

    if (receivedEvent.type == UIEventTypeRemoteControl) {

        switch (receivedEvent.subtype) {

            case UIEventSubtypeRemoteControlTogglePlayPause:
                [self playOrStop: nil];
                break;

            case UIEventSubtypeRemoteControlPreviousTrack:
                [self previousTrack: nil];
                break;

            case UIEventSubtypeRemoteControlNextTrack:
                [self nextTrack: nil];
                break;

            default:
                break;
        }
    }
}

刚刚在 GitHub 上找到解决方案 https://github.com/mattneub/Programming-iOS-Book-Examples/tree/master/bk2ch14p643ducking/ch27p912ducking