美文网首页iOS 开发每天分享优质文章
iOS远程推送、推送语音播报

iOS远程推送、推送语音播报

作者: _Royal_ | 来源:发表于2018-08-22 16:02 被阅读204次

    注册极光推送

    - (void)initJPUSHWithOptions:(NSDictionary *)launchOptions {
        // 添加初始化APNs代码
        // notice: 3.0.0及以后版本注册可以这样写,也可以继续用之前的注册方式
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            // 可以添加自定义categories
            [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
        } else {
            // categories 必须为nil
            [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
        }
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
        
        // ---------- 添加初始化JPush代码 BEGIN ----------
        // Optional
        // 获取IDFA
        // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
        NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        NSString * appKey = @"45b7b***********70f1c1";
        NSString * channel = @"App Store";
        
    #if DEBUG
        BOOL isProduction = YES;
        
        NSSet *set = [NSSet setWithObject:@"ios"];
        NSInteger xuliehao = 123456789;
        [JPUSHService addTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            NSLog(@"极光推送设置tag成功!");
        } seq:xuliehao];
    #else
        BOOL isProduction = YES;
    #endif
        
        // Required
        // init Push
        // notice: 2.1.5版本的SDK新增的注册方法,改成可上报IDFA,如果没有使用IDFA直接传nil
        // 如需继续使用pushConfig.plist文件声明appKey等配置内容,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
        [JPUSHService setupWithOption:launchOptions appKey:appKey channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
        // ---------- 添加初始化JPush代码 END ----------
    }
    

    实现极光推送回调

    // iOS 10 --- 前台显示推送,程序运行时接收到推送消息
    - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
        
        NSDictionary * userInfo = notification.request.content.userInfo;
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    
        // 在这里处理推送
        
        // 执行这个方法,提醒用户用推送,有Badge、Sound、Alert三种提醒类型
        completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);
    }
    
    // iOS 10 --- 后台显示推送,点击进来的时候,接收推送消息
    - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
        
        NSDictionary * userInfo = response.notification.request.content.userInfo;
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
           
        // 在这里处理推送
        
        // 系统要求执行这个方法
        completionHandler();
    }
    

    实现系统回调

    // 收到推送消息,Required, iOS 7 Support
    // content-available 或者 mutable-content 推送(普通的 Remote Notification不调用此参数,非普通的 Remote Notification在程序非杀死状态都会调用此函数,所以语音播报会再这里调用)
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
        
        [JPUSHService handleRemoteNotification:userInfo];
        completionHandler(UIBackgroundFetchResultNewData);
        
        // 取得 APNs 标准信息内容
        NSDictionary *aps = [userInfo valueForKey:@"aps"];
        NSString *content = [aps valueForKey:@"alert"];         //推送显示的内容
        // 语音播报
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self playPushNotifationVideo:content];
        });
    }
    
    // 收到推送消息,Required,For systems with less than or equal to iOS6
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    
    // 本地推送
    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
        
    }
    

    语音播报

    1. 需要导入头文件#import <AVFoundation/AVFoundation.h>
    2. 实现实例变量AVSpeechSynthesizer *play;UIBackgroundTaskIdentifier _bgTaskId;
    //实现一下backgroundPlayerID:这个方法:
    + (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId {
        //设置并激活音频会话类别
        AVAudioSession *session=[AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        [session setActive:YES error:nil];
        //允许应用程序接收远程控制
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        //设置后台任务ID
        UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
        newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
        if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
        {
            [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
        }
        return newTaskId;
    }
    
    - (void)playPushNotifationVideo:(NSString *)string {
        play = [[AVSpeechSynthesizer alloc] init];
        //play.delegate=self;
        AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];    // 设置发音,这是中文普通话
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];        // 需要转换的文字
        utterance.rate = 0.5;               // 设置语速,范围0-1,注意0最慢,1最快;
        utterance.voice = voice;
        [play speakUtterance:utterance];    // 开始
    }
    

    语音播报只能在前台进行播报,无法再后台进行播报,所以需要进行以下开发:

    //程序失去焦点
    - (void)applicationWillResignActive:(UIApplication *)application {
        //开启后台处理多媒体事件
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        AVAudioSession *session=[AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        //后台播放
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        //这样做,可以在按home键进入后台后 ,播放一段时间,几分钟吧。
        //但是不能持续播放网络歌曲,若需要持续播放网络歌曲,还需要申请后台任务id,具体做法是:
        //其中的_bgTaskId是后台任务UIBackgroundTaskIdentifier _bgTaskId;
        _bgTaskId = [AppDelegate backgroundPlayerID:_bgTaskId];
    }
    

    注意:程序杀死之后,无法进行语音播报;

    参考文章:
    1. 关于APP上语音播报的完整实现(iOS篇)
    2. iOS - 根据推送消息进行语音播报
    3. iOS,推送+后台语音播报

    相关文章

      网友评论

        本文标题:iOS远程推送、推送语音播报

        本文链接:https://www.haomeiwen.com/subject/nqdyiftx.html