Play song in Notification

本小妞迷上赌 提交于 2021-01-29 05:30:07

问题


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.


回答1:


Add custom sound to your local notification

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

For Push notification Add this to payload..

{
 aps =
 {
    alert = "message";
    sound = "pushSound.caf";//this file will have to your bundle
   };
}



回答2:


You need to make couple of changes in plist file.

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

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

Code

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


来源:https://stackoverflow.com/questions/43224858/play-song-in-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!