iOS:Objective -C如何在应用程序处于后台模式时更改推送通知声音有效负载?

时间:2017-06-12 05:26:21

标签: ios objective-c audio push-notification background

在我的应用程序中,我允许用户更改push notification的声音。

当用户选择Sound-ASound-B时,当应用处于有效模式时,它会正常播放。

但当应用位于background mode时,它始终会播放Sound-A,因为push notification payload sound设置为Sound-A.

{
   "aps": {
   "alert": "My News!",
   "sound": "sound_a.mp3",
    }
 }

如何用用户选择的声音覆盖它。

我已将用户选定的声音存储在app preferences中,我尝试更换它,但它无效。

NSString *soundName = [self getSoundTrack];
[pushArray setObject:soundName forKey:@"sound"];

3 个答案:

答案 0 :(得分:1)

您可以使用AV播放器在后台播放通知声音。在我的应用中正常工作

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;


 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
 _audioPlayer=nil;
  if(application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground ){
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                     pathForResource:@“soundName”
                                     ofType:@"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
                initWithContentsOfURL:url
                error:&error];
if (error)
{
    NSLog(@"Error in audioPlayer: %@",
    [error localizedDescription]);
} else {
    [_audioPlayer prepareToPlay];
}
[_audioPlayer play];
}

答案 1 :(得分:0)

在后台模式下接收时,您无法更改ios应用中的声音。要播放的声音是在有效载荷中发送的。如果您想要用户选择的播放声音,您应该能够将该数据存储在后端

答案 2 :(得分:0)

如果您想使用iOS客户端代码以编程方式更改声音,您可以让服务器发送静音推送通知,然后在您的应用被唤醒到后台时发送带有配置声音的本地通知。

然而,更简单的解决方案是其他人所说的。用户更改声音设置时更新服务器。