app收款语音后台播报方案

2020-03-31 更新:

这篇文章在后台,进程上有问题 请查看我的这篇文章https://juejin.im/post/5def4e70e51d45580d4aa0df

通常情况下,app在ios上后台运行时,发送的推送无法被app监听,并执行自定义操作。
这个时候,需要发起Remote Notifications(ios7开始支持后台)
ios7和ios6对比:
app收款语音后台播报方案_第1张图片
可以看出,ios7的消息可供我们自定义后再发出(服务端需要设置content-available: 1 )。
这样,在客户端可以在

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

方法里监听到后台运行的回调,在这里可以发起请求,播报语音等操作:
1,直接播报语音:
在xcode项目的根目录级的plugins目录下的AppDelegate+JPush.m文件下,找到(没有的话直接在Classes目录下的AppDelegate.m添加)上面的那个方法
这个方法可处理app后台运行时的回调



#import "AppDelegate+JPush.h"
#import "JPushPlugin.h"
#import 
#import 
#import 
#import "JPushDefine.h"
#import  // 用于播报语音

@implementation AppDelegate (JPush)

+(void)load{
    Method origin1;
    Method swizzle1;
    origin1  = class_getInstanceMethod([self class],@selector(init));
    swizzle1 = class_getInstanceMethod([self class], @selector(init_plus));
    method_exchangeImplementations(origin1, swizzle1);
}

-(instancetype)init_plus{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidLaunch:) name:UIApplicationDidFinishLaunchingNotification object:nil];
    return [self init_plus];
}

NSDictionary *_launchOptions;
-(void)applicationDidLaunch:(NSNotification *)notification{
   
    if (!_jpushEventCache) {
        _jpushEventCache = @{}.mutableCopy;
    }

    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
      NSDictionary *event = @{@"registrationId": registrationID?:@""};
      [JPushPlugin fireDocumentEvent:JPushDocumentEvent_receiveRegistrationId jsString:[event toJsonString]];
    }];
  
  if (notification != nil &&
      [[UIDevice currentDevice].systemVersion floatValue] < 10.0) {// iOS 10 以后通过 openNotification 这个回调触发事件。
        if (notification.userInfo) {
            
          if ([notification.userInfo valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey]) {
            [JPushPlugin fireDocumentEvent:JPushDocumentEvent_OpenNotification
                                  jsString:[[self jpushFormatAPNSDic: notification.userInfo[UIApplicationLaunchOptionsRemoteNotificationKey]] toJsonString]];
          }
          
          if ([notification.userInfo valueForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
            UILocalNotification *localNotification = [notification.userInfo valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
            NSMutableDictionary *localNotificationEvent = @{}.mutableCopy;
            localNotificationEvent[@"content"] = localNotification.alertBody;
            localNotificationEvent[@"badge"] = @(localNotification.applicationIconBadgeNumber);
            localNotificationEvent[@"extras"] = localNotification.userInfo;

            [JPushPlugin fireDocumentEvent:JPushDocumentEvent_OpenNotification jsString:[localNotificationEvent toJsonString]];
          }
        }
    }
  
  [JPUSHService setDebugMode];
  
  NSString *plistPath = [[NSBundle mainBundle] pathForResource:JPushConfig_FileName ofType:@"plist"];
  NSMutableDictionary *plistData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  NSNumber *delay       = [plistData valueForKey:JPushConfig_Delay];
  
  _launchOptions = notification.userInfo;
  
  if (![delay boolValue]) {
    [self startJPushSDK];
  }
}

-(void)startJPushSDK{
    [self registerForRemoteNotification];
    [JPushPlugin setupJPushSDK:_launchOptions];
}

- (void)jpushSDKDidLoginNotification {
  NSDictionary *event = @{@"registrationId": JPUSHService.registrationID};
  [JPushPlugin fireDocumentEvent:JPushDocumentEvent_receiveRegistrationId jsString:[event toJsonString]];
}

- (NSMutableDictionary *)jpushFormatAPNSDic:(NSDictionary *)dic {
  NSMutableDictionary *extras = @{}.mutableCopy;
  for (NSString *key in dic) {
    if([key isEqualToString:@"_j_business"]      ||
       [key isEqualToString:@"_j_msgid"]         ||
       [key isEqualToString:@"_j_uid"]           ||
       [key isEqualToString:@"actionIdentifier"] ||
       [key isEqualToString:@"aps"]) {
      continue;
    }
    extras[key] = dic[key];
  }
  NSMutableDictionary *formatDic = dic.mutableCopy;
  formatDic[@"extras"] = extras;
  return formatDic;
}

-(void)registerForRemoteNotification{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else if([[UIDevice currentDevice].systemVersion floatValue] < 8.0){
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    [JPUSHService handleRemoteNotification:userInfo];

    [JPushPlugin fireDocumentEvent:JPushDocumentEvent_ReceiveNotification jsString:[userInfo toJsonString]];
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
   
    NSString *eventName;
    // 根据app运行情况,发送不同的事件给document监听,后台运行时(根据[UIApplication shareApplication].applicationState === UIApplicationStateBackground来判断)的事件推送给document
    switch ([UIApplication sharedApplication].applicationState) {
      case UIApplicationStateBackground:
        eventName = JPushDocumentEvent_BackgroundNotification;
        break;
      default:
        eventName = JPushDocumentEvent_ReceiveNotification;
        break;
    }
    
    [JPUSHService handleRemoteNotification:userInfo];
    [JPushPlugin fireDocumentEvent:eventName jsString:[[self jpushFormatAPNSDic:userInfo] toJsonString]];// 发起事件和推送
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      completionHandler(UIBackgroundFetchResultNewData);
    });
   // 可以在此处进行语音播报,这里可以取到userInfo内容进行播报
   AVSpeechSynthesizer * synthsizer = [[AVSpeechSynthesizer alloc] init];
   AVSpeechUtterance * utterance = [[AVSpeechUtterance alloc] initWithString:@"语音播报生效了"];//需要转换的文本
   utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//国家语言
   utterance.rate = 0.4f;//声速
   [synthsizer speakUtterance:utterance];
}

-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler{
  NSMutableDictionary *userInfo = @{}.mutableCopy;
  
  if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    userInfo = [self jpushFormatAPNSDic:notification.request.content.userInfo];
  } else {
    UNNotificationContent *content = notification.request.content;
    userInfo[@"content"] = content.body;
    userInfo[@"badge"] = content.badge;
    userInfo[@"extras"] = content.userInfo;
    userInfo[@"identifier"] = notification.request.identifier;
  }
  
  completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
  
  if ([userInfo[@"aps"][@"content-available"] isEqualToNumber:@(1)]) {// content-available 当用户开启后台推送是,防止触发两次事件
    return;
  }
  
  [JPushPlugin fireDocumentEvent:JPushDocumentEvent_ReceiveNotification jsString:[userInfo toJsonString]];
  
}

-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
  UNNotification *notification = response.notification;
  NSMutableDictionary *userInfo = @{}.mutableCopy;
  
  if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    userInfo = [self jpushFormatAPNSDic:notification.request.content.userInfo];
  } else {
    UNNotificationContent *content = notification.request.content;
    userInfo[@"content"] = content.body;
    userInfo[@"badge"] = content.badge;
    userInfo[@"extras"] = content.userInfo;
    userInfo[@"identifier"] = notification.request.identifier;
  }
  
  [JPushPlugin fireDocumentEvent:JPushDocumentEvent_OpenNotification jsString:[userInfo toJsonString]];
  completionHandler();
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  NSMutableDictionary *localNotificationEvent = @{}.mutableCopy;
  localNotificationEvent[@"content"] = notification.alertBody;
  localNotificationEvent[@"badge"] = @(notification.applicationIconBadgeNumber);
  localNotificationEvent[@"extras"] = notification.userInfo;
  
  [[NSNotificationCenter defaultCenter] postNotificationName:JPushDocumentEvent_ReceiveLocalNotification object:localNotificationEvent];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //  [application setApplicationIconBadgeNumber:0];
    //  [application cancelAllLocalNotifications];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //  [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

@end

2,在app内监听JPush发送过来的事件,发起播报和请求等
监听上诉代码中的发起给document的jpush.backgroundNotification事件:

// ios在后台运行时,jpush推送过来的事件监听
document.addEventListener("jpush.backgroundNotification", onBackgroundNotification, false);

function onBackgroundNotification(notification) {
       if (ServerConfig.businessConfigValue.isOpenBroadcast) {
       	 // 语音播报的调用
        	readSalePatTrade(notification);
       }
}
// 处理收款播报
 function readSalePatTrade(notice) {
     if ((notice.path === 'eventmenu.paymentRecord') || (notice.extras['cn.jpush.android.EXTRA'].path === 'eventmenu.paymentRecord')) {
         var orderSn = notice.param || notice.extras['cn.jpush.android.EXTRA'].param;
         psisServices.postEncode('/admin/inner/pay/getSalePayTrade.ac?businessSn=' + orderSn, {}, true)
             .success(function (res) {
                 if (res = res.object) {
                     if (res.tradeStatus === 'success') {
                         mediaFactory.audio.start(res.amount);// 这里的播报请查看我的另一篇文章《cordova-plugin-background-mode+cordova-plugin-media实现APP在ios后台运行时发起语音播报》
                     }
                 }
             });
     }
 }

详情请查看:
https://www.jianshu.com/p/ef344a294f99
https://www.jianshu.com/p/a41cb018f0b5
https://docs.jiguang.cn/jpush/client/iOS/ios_new_fetures/#ios-7-background-remote-notification
https://docs.jiguang.cn/jpush/client/iOS/ios_api/#apns

你可能感兴趣的:(JPush)