描述:
App在后台时接收到推送消息时,怎么去语音播报?
解决方案1:
后台语音播报:
1.推送唤醒(程序在收到推送时可以在后台运行代码)
2.执行代码
- 1.启用推送唤醒
和上面的后台获取类似,更改Info.plist,在UIBackgroundModes下加入remote-notification即可开启,当然同样的更简单直接的办法是使用Capabilities。
- 2.更改推送的payload
在iOS7中,如果想要使用推送来唤醒应用运行代码的话,需要在payload中加入content-available,并设置为1。
{"aps":{"content-available":1,"alert":"今天是个好天气"}}
"content-available":1 推送唤醒
"alert":"" 推送内容
"badge":1 app右上角数字
“sound”:”default” 默认声音
aps {
content-available: 1
alert: {...}
}
- 3.实现推送唤醒代码并通知系统
最后在appDelegate中实现-application:didReceiveRemoteNotification:fetchCompletionHandle:。这部分内容和上面的后台获取部分完全一样,在此不再重复。
//接收到推送消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"remote: %@", userInfo);
//回调
completionHandler(UIBackgroundFetchResultNewData);
//语音播报
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:userInfo[@"aps"][@"alert"]];
AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
[synth speakUtterance:utterance];
}