简体   繁体   中英

How to play separate audio for different notification responses in iOS using Swift?

I have a scenario, I want to play different audios using AVAudioPlayer for different notification responses.

for example, when notification response is yes I want to play audio1 and similarly, for fail , audio2 . My code is as below,

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
//Presenting audioController from here
}

audioController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    var player:AVAudioPlayer = AVAudioPlayer()
    if notificationResponse == "yes" {
        audioPath =  NSBundle.mainBundle().pathForResource("audio1", ofType: "mp3")
    } else if notificationResponse == "no" {
        audioPath = NSBundle.mainBundle().pathForResource("audio2", ofType: "mp3")
    }
    player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
    player.numberOfLoops = -1
    player.play()
}

The problem is, when both notification arrives at the same time, view controllers are presenting twice and both audios are playing.

How to stop playing the older audio when newer notification is arrived?

Make player var as property for audioController.swift then make your audioController.swift class's object global in AppDelegate then

add a check if audioController.swift class's object is already presented, for that check presentedViewController is nil or not nil on which instance you are presenting it, before presenting in didReceiveRemoteNotification .

If its already presented then stop player and change player's audioPath without presenting audioController again.

var audioC : audioController // Its you global var in AppDelegate

//Use this code after adding a check the audioC is already presented or not in didReceiveRemoteNotification
audioC.player.stop() // Stop previous running audio
audioC.player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: newAudioPath!)) // newAudioPath will be your new audio files path
audioC.player.play() // Play the new audio.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM