0
我想播放一首歌曲。當有通知時。當應用程序處於前景模式時,我的代碼工作正常。我想在應用程序處於後臺模式時播放歌曲。請幫忙。在通知中播放歌曲
我想播放一首歌曲。當有通知時。當應用程序處於前景模式時,我的代碼工作正常。我想在應用程序處於後臺模式時播放歌曲。請幫忙。在通知中播放歌曲
添加自定義的聲音到本地通知
雨燕3.0
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
var state: UIApplicationState = application.applicationState
if state == .active {
var soundID: SystemSoundID
var mainBundle: CFBundleRef = CFBundleGetMainBundle()
var ref: CFURLRef? = CFBundleCopyResourceURL(mainBundle, ("mySoundName.wav" as? CFString), nil, nil)
AudioServicesCreateSystemSoundID(ref, soundID)
AudioServicesPlaySystemSound(soundID)
}
else {
// Push Notification received in the background
}
}
推送通知 一下添加到有效載荷..
{
aps =
{
alert = "message";
sound = "pushSound.caf";//this file will have to your bundle
};
}
你需要做一些修改在plist文件中。
1.)將所需背景模式設置爲App播放音頻。
2)套裝應用程序不能在後臺運行到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()
}
}
增加了3.0版本。 – Saranjith
它在我的應用程序中工作... – Saranjith