0

可能这是一个重复的问题,但没有一个解决方案对我有用。我已经尝试了几乎所有东西。

正在播放的信息不会在锁定屏幕中更新。

Swift 版本:5 & iOS 版本:13

这是我的代码

func setupRemoteCommandCenter() {
        UIApplication.shared.beginReceivingRemoteControlEvents()

        let commandCenter = MPRemoteCommandCenter.shared()
        

        commandCenter.playCommand.addTarget { event in
            return .success
        }
        

        commandCenter.pauseCommand.addTarget { event in
            return .success
        }
        

        commandCenter.nextTrackCommand.addTarget { event in
            return .success
        }
        

        commandCenter.previousTrackCommand.addTarget { event in
            return .success
        }
    }
    
    func updateLockScreen() {
        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyArtist] = "Artist"
        nowPlayingInfo[MPMediaItemPropertyTitle] = "title"
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }

一种方法是从 viewDidLoad 中调用,即

override func viewDidLoad() {
        super.viewDidLoad()
        AudioManager.shared.audioManageDelegate = self
        // Do any additional setup after loading the view.
        setupRemoteCommandCenter()
    }

另一个是从 playbuttonAction 方法调用的,即

@IBAction func togglePlayPauseButton(sender: UIButton) {
        //play pause button
        sender.isSelected = !sender.isSelected
        //updateLockScreen() //I checked it from calling here also
        if sender.isSelected {
            AudioManager.shared.playMusic()
        } else {
            AudioManager.shared.pauseMusic()
        }
        updateLockScreen()
    }

我的 Appdelegate 在这里

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        setUPforbackground()
        return true
    }

    func setUPforbackground() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
            print("Playback OK")
            try AVAudioSession.sharedInstance().setActive(true)
            print("Session is Active")
        } catch {
            print(error)
        }
    }

调用updateLockScreen()之前调用playMusic()也没有结果。我在这里想念什么吗?

4

1 回答 1

0

仔细分析代码后,我发现

try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])

抛出错误所以我将其更改为以下

try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)

希望它会帮助某人。谢谢你。

于 2020-07-03T11:47:22.843 回答