收到通知时播放声音在开发中有效但在生产中无效

Playing sound when receiving notification worked in dev but not in production

我想在收到特定通知时播放声音,无论是否打开静音模式。

我使用 AVFoundation 框架在开发模式下工作。所以在 AppDelegate didFinishLaunchingWithOptions 方法中我初始化 AVAudioSession

NSError *audioSessionError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&audioSessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&audioSessionError];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

if(audioSessionError) {
    NSLog(@"[AppDelegate] audioSessionError: %@", audioSessionError);
}

我用didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler的方法来判断app是否在后台,通知是播放声音的通知。

if(application.applicationState == UIApplicationStateBackground) {        
    NSDictionary *aps = [userInfo objectForKey:@"aps"];

    if([[aps valueForKey:@"category"] isEqualToString:@"alarm"]) {
        NSString *path = [NSString stringWithFormat:@"%@/alarm.wav", [[NSBundle mainBundle] resourcePath]];
        NSURL *soundUrl = [NSURL fileURLWithPath:path];

        NSError *audioPlayerError = nil;
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&audioPlayerError];

        if(audioPlayerError) {
            NSLog(@"[AppDelegate] audioPlayerError: %@", audioPlayerError);
        } else {
            NSLog(@"[AppDelegate] audioPlayer play call");
            [self.audioPlayer play];
        }
    }

    completionHandler(UIBackgroundFetchResultNewData);
} else {
    completionHandler(UIBackgroundFetchResultNoData);
}

背景模式 audioremote-notification info.plist 中的键已设置。

一切正常所以我在没有对 TestFlight 进行任何更改的情况下推送了应用程序。当应用程序现在收到通知时,会显示警报,但在静音模式打开时不会播放声音。所以我再次在 dev 中测试了它,得到了相同的结果。收到并显示通知,但未播放声音。

我不知道为什么在将它推送到 TestFlight 之前它在开发中工作,而在它之后是在生产中工作还是在开发中工作。每次都收到通知,只是声音不响了。

有人知道这是怎么发生的吗?

所以,我找到了解决问题的办法。

在初始化 AVAudioSessionAppDelegate.m 文件中,我更改了

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]; 

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&audioSessionError];

使用新选项 AVAudioSessionCategoryOptionMixWithOthers,它适用于开发和生产。