ios 用户收到推送通知时如何播放自定义声音文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21179630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to play custom sound file when user get push notification?
提问by Parveen Tyagi
I have a sound file in the app bundle, i want to play that sound file when user will get push notification.
我在应用程序包中有一个声音文件,我想在用户收到推送通知时播放该声音文件。
IS it possible in iOS if yes, then please suggest the way to achieve this.
如果是,是否可以在 iOS 中使用,那么请建议实现此目的的方法。
Thanks,
谢谢,
回答by Bhavin_m
To play this sound you must specify the filename of the sound in the notification payload. For example, lets say you've added a sound file named example.caf into your application, we can play this sound with the notification payload as below:
要播放此声音,您必须在通知负载中指定声音的文件名。例如,假设您在应用程序中添加了一个名为 example.caf 的声音文件,我们可以使用通知负载播放此声音,如下所示:
{
aps =
{
alert = "test example notification message";
sound = "example.caf";
};
}
Then the custom sound will play when your notification arrives.
然后,当您的通知到达时,将播放自定义声音。
回答by morroko
Use this method in your app delegte class.
在您的应用委托类中使用此方法。
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive)
{
NSLog(@"User Info : %@", [userInfo description]);
NSLog(@"User Info Alert Message : %@", [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
NSString *messageString = [NSString stringWithFormat:@"%@", [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
NSString *playSoundOnAlert = [NSString stringWithFormat:@"%@", [[userInfo objectForKey:@"aps"] objectForKey:@"sound"]];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],playSoundOnAlert]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
}
}