Swift. Receive remote control events to work with

2019-02-20 17:37发布

As I understand, in order to show music player on lock screen, writing the following code is not enough.

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

My app also should be able to receive remote control events

So, how to do that in Swift?

I found this from Apple Documentation, but it's for 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;
        }
    }
}

登录 后发表回答