Swift. Receive remote control events to work with MPNowPLayingInfoCenter

那年仲夏 提交于 2019-12-04 02:15:42

问题


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;
        }
    }
}

回答1:


Just found solution on GitHub https://github.com/mattneub/Programming-iOS-Book-Examples/tree/master/bk2ch14p643ducking/ch27p912ducking



来源:https://stackoverflow.com/questions/28173174/swift-receive-remote-control-events-to-work-with-mpnowplayinginfocenter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!