在通知中播放歌曲

时间:2017-04-05 07:41:18

标签: swift push-notification swift3 apple-push-notifications

我想要播放一首歌。当通知到来时。当应用程序是前台模式时,我的代码工作正常。当应用处于后台模式时,我想播放一首歌。请帮忙。

2 个答案:

答案 0 :(得分:0)

将自定义声音添加到本地通知

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

答案 1 :(得分:0)

您需要在plist文件中进行一些更改。

1。)将所需的背景模式设置为App播放音频。

2。)设置应用程序不在后台运行到是

<强>代码

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()
}
}