上个版本的开发计划中产品同学建议在我们的商家版App中做后台语音播报功能,在评审的时候我就在想,完全可以通过Push静默推送来实现后台播放音频来实现(后续事实证明,这是个大坑)。
关于静默推送 推荐大家看一下https://www.jianshu.com/p/c211bd295d58
好了,最后通过push和backGroundModes实现了在后台语言播放的功能,工程的配置:
在iOS 10 UNNotificationServiceExtension 刚出现的时候了解过,然后在后续没有用到就忘的差不多了,在对它进一步了解之后,我发现它完全能够在不开启后台运行相关功能的情况下来实现语音播报功能,好吧,开始动手:
在你的功能首先创建UNNotificationServiceExtension target
创建好了把相关音频文件导入:
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
// Modify the notification content here...
//self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
[[AVAudioSession sharedInstance] setActive:YES error:NULL];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
NSDictionary *userInfo = self.bestAttemptContent.userInfo;
NSDictionary * aps = [userInfo objectForKey:@"aps"];
NSString * soundCommand = [aps valueForKey:@"soundCommand"];
[self playSoundsWithSoundCommand:soundCommand];
self.contentHandler(self.bestAttemptContent);
}
/*播放*/
-(void)playWithFileUrlString:(NSString *)fileURLString{
if (![fileURLString length]) {
return;
}
AVAudioSession * session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
BOOL ret = [session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSLog(@"%d",ret);
NSURL *fileURL = [[NSBundle mainBundle]URLForResource:fileURLString withExtension:@".mp3"];
static SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(fileURL), &soundID);
AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
NSLog(@"播放完成");
});
}
复制代码
记住了在做完相关操作之后再调用self.contentHandler(self.bestAttemptContent);方法 进入墓碑模式(不执行应用程序的任何代码)
还有很重要的一点,记住push的试试让后台同学要加入一个参数"mutable-content" = 1;,不然我们的扩展类方法是拦截不到推送的哦,要和alert 同级的,位置不要错。
接下来运行-测试,完美实现。打包,然后又报错了,看了原因是因为扩展target和我的原来工程的签名不是同一team,这时候就要用的appid创建的时候创建一个通配符appid了。
在你开发者中心创建一个通配符appid包含到你的扩展应用下,然后生成相关开发和生成Profile文件,下载下来,然后打包。成功!!!
接下来就是等待苹果爸爸的审核了,不过十拿九稳啦~