问题
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