小知识点上海快风信息科技有限公司临时收藏

iOS,APP退到后台,获取推送成功的内容并且语音播报内容。

2017-05-05  本文已影响7285人  Sylars

各位老铁们,很抱歉,之前的文章内容我已经彻底删除了,毕竟现在iOS 11都有了,现在做推送,想语音报内容,又不想程序被杀死,这是不可能滴哈哈!不过我确实有做让程序一直挂在后台运行的,坚持最高的好像有48个小时。 我靠!听完都震精!这不是对手机有危害吗!这种程序上架能过的都是毒瘤哈哈哈!

好了,不扯别的了,其实我们没必要让程序一直保持在运行当中,我们可以给他一个推送,让程序唤醒,执行里面的推送扩展方法就可以。有人说支付宝可以播报,哪怕程序被杀死以后也可以,老实说,你可以把支付宝的推送给关闭了,你再试试收付款,你看看能不能播报了? 测试完你很快就能得知支付宝利用的也是推送扩展。 推送扩展哪方面的呢?

iOS 10 UNNotificationServiceExtension ! 这个具体各位大佬们可以直接百度搜索一下就好。我呢就直接将重要的代码给各位展示出来。请看下面:

1.首先后端要给你个推送测试内容,内容模板如下:

( 要记住在aps里一定要有"mutable -content"这个字段,alert 这个用字符串就可以,不用字典。当然字典也行,后面可以获取里面字符串也行。)

推送模板
2.选择创建“NotificationServiceExtension” 

(看仔细了,不要问我为
什么不选左边的,你可以先百度了解一下推送扩展,就了解了。)


image image.png image.png

3.NotificationService.m文件内的代码,这就是iOS10的推送扩展

//
//  NotificationService.m
//  GYNotificationService
//
//  Created by Sylar on 2018/4/12.
//  Copyright © 2018年 Sylar. All rights reserved.
//

#import "NotificationService.h"
#import <AVFoundation/AVFAudio.h>

@interface NotificationService ()<AVSpeechSynthesizerDelegate>

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);

@property (nonatomic, strong) UNMutableNotificationContent *attemptContent;

@property (nonatomic, strong) AVSpeechSynthesizer *aVSpeechSynthesizer;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
   
    self.contentHandler = contentHandler;

    
    self.attemptContent = [request.content mutableCopy];
    self.aVSpeechSynthesizer = [[AVSpeechSynthesizer alloc] init];
    // Modify the notification content here...
    NSString *str = self.attemptContent.userInfo[@"aps"][@"alert"];
    AVSpeechUtterance * aVSpeechUtterance = [[AVSpeechUtterance alloc] initWithString:str];
    
    aVSpeechUtterance.rate = AVSpeechUtteranceDefaultSpeechRate;
    
    aVSpeechUtterance.voice =[AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    
    [self.aVSpeechSynthesizer speakUtterance:aVSpeechUtterance];

}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.attemptContent);
}

@end
  1. 配置扩展需要的开关


    image.png
image.png

加上:“App Transport Security Settings” “Allow Arbitrary Loads”

5.把扩展里的Deployment Target 改成 10.0,毕竟扩展10.0以后才能用哈。


image.png

6.到这一步基本已经可以了。然后先运行一下扩展,然后再选择运行一下项目


image.png

之后你就可以感受到推送的快感,你可以将程序杀死。如果你发现测试了但没声音,你可能需要换个手机试一下,推送是必须要打开的,不行的话,卸载APP重新安装就可以了。其实推送扩展没啥代码的,很容易的,如果你觉得系统机器人声音难听,支付宝的好听,那是因为他们在扩展里加了判断,声音是由多个音频文件合成的。但是都是收款,需要的话可以加群直接要,群内也有示范demo,另外需要注意的是iOS 10以后才支持,10以前是不支持的哦!如果有帮助到您,请点赞+关注!爱你么么哒。想进群先打赏哈哈~

上一篇下一篇

猜你喜欢

热点阅读