分享一个类似支付宝收款提醒的语音播报,我这里推送配的是个推,集成配置都可以参照个推文档中心,文档介绍步骤都很详细。
1、打开推送Capabilities---Push Notifications
2、开启远程推送Capabilities---Background Modes---Remote Notifications
3、新建UNNotification Service Extension
File---New---Target,选UNNotification Service Extension
新建完成后你会发现多了几个文件
4、开始编码
添加声音依赖库AVFoundation,在NotificationService.m中代码如下,现在可以去个推官方推一条试试了。后台推的是透传消息,在项目在前台运行时,可以自行添加声音方法。
#import "NotificationService.h"
#import <AVFoundation/AVSpeechSynthesis.h>
#import <MediaPlayer/MediaPlayer.h>
@interface NotificationService ()<AVSpeechSynthesizerDelegate>
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@end
@implementation NotificationService
- (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];
self.contentHandler(self.bestAttemptContent);
[self startSpeaking:self.bestAttemptContent.body];
}
- (void)startSpeaking:(NSString *)words{
// 创建语音合成器
AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
synthesizer.delegate = self;
// 设置语音
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
// 转换文本
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:words];
utterance.voice = voice;
// 语速
utterance.rate = 0.8;
// 朗读的内容
[synthesizer speakUtterance:utterance];
}
#pragma mark AVSpeechSynthesizerDelegate
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(@"开始播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"完成播放");
}
@end
5、其他
1)创建UNNotification Service Extension成功后,这里Bundle ID 会自动添加 .MyNotification,不需要重新配置证书
后面选择证书的地方设成默认就行
2)不太了解Notification Servivice Extension的可以先看下这篇文章,作者讲解的很详细
1413

被折叠的 条评论
为什么被折叠?



