How do I get my sound to play when a remote notification is received?

后端 未结 2 577
天涯浪人
天涯浪人 2021-01-03 06:50

I\'m trying to automatically play a sound file (that is not part of my app bundle and is not a notification sound) upon receiving a remote notification. I want this to happe

2条回答
  •  抹茶落季
    2021-01-03 07:34

    If you call AVAudioSession:setActive:error: and AVAudioSession:setCatagory:withOptions:error: and create your AVPlayer before going into the background, you can then play your sound. For example:

        // Make sure this is run BEFORE entering background.
        [[AVAudioSession sharedInstance] setActive:YES error:&error];
        if(error != nil){
            NSLog(@"ERROR: %@", error.localizedDescription);
        }
        else {
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];
            if(error != nil){
                NSLog(@"ERROR: %@", error.localizedDescription);
            }
            else {
                self._player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlOfFileToPlay error:&error];  
                if(error != nil){
                    [[AVAudioSession sharedInstance] setActive:NO error:&error];
                    NSLog(@"ERROR: %@", error.localizedDescription);
                }
            }
        }
        //You can then do this in application:didReceiveRemoteNotification:fetchCompletionHandler:
        [backgroundPlayer.player play]; 
    

    Of course I am assuming that you already have the Capabilities for Background Modes set for Background fetch and Remote notifications.

    I will also warn that if you call AVAudioSession:setActive:error: too early, other applications might change things on you.

    Also, if you set your application NOT to run in the background (Info.plist: UIApplicationExitsOnSuspend ), when it receives a "Notification" (local or remote) and you have activated an AVAudioSession, like the above code, it will play the sound in the notification payload regardless of if the application is set to silent or vibrate mode, which is actually how alarms do it. Of course this will not work if you need to poll the server in response to a remote notification. See here.

提交回复
热议问题