在通知中播放歌曲 [英] Play song in Notification

查看:95
本文介绍了在通知中播放歌曲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想播放一首歌.收到通知时.当应用程序为前台模式时,我的代码工作正常.我想在应用程序处于后台模式时播放歌曲.请帮忙.

I want to play a song. When a notification comes. My code is working fine when the app is foreground mode. I want to play a song when the app is in background mode. Please help.

推荐答案

您需要在plist文件中进行几处更改.

You need to make couple of changes in plist file.

1.)将必需的背景"模式设置为App播放音频.

1.) Set Required background mode to App plays audio.

2.)将设置应用程序不在后台运行"设置为是"

2.) Set Application does not run in background to YES

代码

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
var state: UIApplicationState = application.applicationState
if state == .active {
    print("User Info : \(userInfo.description)")
    print("User Info Alert Message : \(userInfo["aps"]["alert"])")
    var messageString: String? = "\((userInfo["aps"] as? String)?["alert"] as? String)"
    var playSoundOnAlert: String? = "\((userInfo["aps"] as? String)?["sound"] as? String)"
    var url = URL(fileURLWithPath: "\(Bundle.main.resourcePath)/\(playSoundOnAlert)")
    var error: Error?
    audioPlayer = try? AVAudioPlayer(contentsOf: url)
    audioPlayer.numberOfLoops = 0
    audioPlayer.play()
}
}

这篇关于在通知中播放歌曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆