迅速。接收远程控制事件以使用MPNowPLayingInfoCenter

时间:2015-01-27 14:44:55

标签: ios swift remote-control 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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)