Swift 5.1 NSInternalInconsistencyException 错误

Swift 5.1 NSInternalInconsistencyException error

我正在更新旧的媒体播放器项目 (Swift 3) 并出现奇怪的错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unsupported action method signature. Must return MPRemoteCommandHandlerStatus or take a completion handler as the second argument.

我在这段代码上遇到了这个错误:

UIApplication.shared.beginReceivingRemoteControlEvents()
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.previousTrackCommand.addTarget(self, action: #selector(handlePrevTrack))

@objc func handlePrevTrack(){
        if playListEpisodes.count == 0 {
            return
        }

        let currentEpisodeIndex = playListEpisodes.firstIndex { (ep) -> Bool in
            return self.episode.title == ep.title && self.episode.author == ep.author
        }

        guard let index = currentEpisodeIndex else { return}
        let nextEpisode:Episode

        if index == 0 {
            nextEpisode = playListEpisodes[playListEpisodes.count - 1]
        }else {
            nextEpisode = playListEpisodes[index - 1]
        }

        self.episode = nextEpisode

 }

Swift 5.1 有什么变化?

根据文档,previousTrackCommand 选择器应该将 MPRemoteCommandEvent 作为第一个参数并且 return MPRemoteCommandHandlerStatus:

func addTarget(handler: (MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus) -> Any

因此您的 handlePrevTrack 函数应声明为:

@objc func handlePrevTrack(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
...
}