iOS远程推送和本地推送总结

因为得到一个新功能:在前台,后台,和锁屏状态下,得到后台通知时语音播报,查阅一些资料并作出总结。为了方便理解以下内容分为三个部分:

  • APP生命周期
  • 合成语音
  • 各个系统下收到通知的逻辑处理

首先我们要先了解APP在各情况下的活跃状态以及涉及的系统方法:
1.首次启动正常前台运行:活跃状态

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
        return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
     NSLog(@" 程序激活 !");
}

2.锁屏状态:挂起->进入后台

- (void)applicationWillResignActive:(UIApplication *)application {
    // 比如:当有电话进来或者锁屏,这时你的应用程会挂起,在这时,UIApplicationDelegate委托会收到通知,调用 applicationWillResignActive 方法,你可以重写这个方法,做挂起前的工作,比如关闭网络,保存数据。
    NSLog(@" 程序挂起 !");
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@" 程序进入后台 !");
}

3.点击home:挂起->进入后台

- (void)applicationWillResignActive:(UIApplication *)application {
    NSLog(@" 程序挂起 !");
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@" 程序进入后台 !");
}

4.后台状态时,点击收到的通知或者icon

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    NSLog(@"程序进入前台 !");
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
     NSLog(@"程序激活 !");
}

二、语音部分
用系统强大的AVSpeechSynthesizer(10_14, 7_0),写成一个单例

+(instancetype)sharedInstance{
    static CRSpeechManger *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[CRSpeechManger alloc] init];
        instance.synthesizer = [[AVSpeechSynthesizer alloc] init];
    });
    return instance;
}

- (void)syntheticVoice:(NSString*)string {
    //  语音合成
    AVSpeechUtterance *speechUtterance = [AVSpeechUtterance speechUtteranceWithString:string];
    //设置语言类别(不能被识别,返回值为nil)
    speechUtterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    //设置语速快慢
    speechUtterance.rate=0.5;//0.5是一个    //语音合成器会生成音频
    [self.synthesizer speakUtterance:speechUtterance];
}

三、通知部分
我们先聊本地通知,其中iOS10是一个分水岭,iOS10以前的系统用UILocalNotification,iOS10以后的系统包括10,系统新增库,增加自定义多媒体消息的功能。
1.发送通知

- (void)pushNotification_IOS10_before{
    UILocalNotification *notif = [[UILocalNotification alloc] init];
    // 发出推送的日期
    notif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    // 推送的内容
    notif.alertBody = @"本地推送语音测试";
    // 可以添加特定信息
    notif.userInfo = @{ @"name": @"123" };
    // 角标
    notif.applicationIconBadgeNumber = 1;
    // 提示音
    notif.soundName = UILocalNotificationDefaultSoundName;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:notif];
}

-(void)pushNotification_IOS_10_after {
    //获取通知中心用来激活新建的通知
    UNUserNotificationCenter * center  = [UNUserNotificationCenter currentNotificationCenter];
    
    UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc]init];
    
    content.body = body;
    content.userInfo = @{@"name":@"123"};
    //通知的提示音
    if ([promptTone containsString:@"."]) {
        UNNotificationSound *sound = [UNNotificationSound soundNamed:promptTone];
        content.sound = sound;
    }
    
    __block UNNotificationAttachment *imageAtt;
    __block UNNotificationAttachment *movieAtt;
    __block UNNotificationAttachment *soundAtt;
    NSString * imageName = @"";
    if ([imageName containsString:@"."]) {
        [self addNotificationAttachmentContent:content attachmentName:imageName options:nil withCompletion:^(NSError *error, UNNotificationAttachment *notificationAtt) {
            
            imageAtt = [notificationAtt copy];
        }];
    }
     NSString * soundName = @"";
    if ([soundName containsString:@"."]) {
        [self addNotificationAttachmentContent:content attachmentName:soundName options:nil withCompletion:^(NSError *error, UNNotificationAttachment *notificationAtt) {
            soundAtt = [notificationAtt copy];
        }];
    }
      NSString * movieName = @"";
    if ([movieName containsString:@"."]) {
        UNNotificationAttachmentOptionsThumbnailTimeKey
        [self addNotificationAttachmentContent:content attachmentName:movieName options:@{@"UNNotificationAttachmentOptionsThumbnailTimeKey":@10} withCompletion:^(NSError *error, UNNotificationAttachment *notificationAtt) {
            movieAtt = [notificationAtt copy];
        }];
    }
    
    NSMutableArray * array = [NSMutableArray array];
    //    [array addObject:soundAtt];
    //    [array addObject:imageAtt];
    //    [array addObject:movieAtt];
    
    content.attachments = array;
    
    //添加通知下拉动作按钮
    NSMutableArray * actionMutableArray = [NSMutableArray array];
    UNNotificationAction * actionA = [UNNotificationAction actionWithIdentifier:@"identifierNeedUnlock" title:@"进入应用" options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction * actionB = [UNNotificationAction actionWithIdentifier:@"identifierRed" title:@"忽略" options:UNNotificationActionOptionDestructive];
    [actionMutableArray addObjectsFromArray:@[actionA,actionB]];
    
    if (actionMutableArray.count > 1) {
        
        UNNotificationCategory * category = [UNNotificationCategory categoryWithIdentifier:@"categoryNoOperationAction" actions:actionMutableArray intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
        [center setNotificationCategories:[NSSet setWithObjects:category, nil]];
        content.categoryIdentifier = @"categoryNoOperationAction";
    }
    
    //UNTimeIntervalNotificationTrigger   延时推送
    //UNCalendarNotificationTrigger       定时推送
    //UNLocationNotificationTrigger       位置变化推送
    
    UNTimeIntervalNotificationTrigger * tirgger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
    
    //建立通知请求
    UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:tirgger];
    
    //将建立的通知请求添加到通知中心
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
             NSLog(@"%@本地推送 :( 报错 %@",identifier,error);
        } else {
             NSLog(@"本地推送 :成功");
        }
       
        
    }];
}

2.注册本地通知

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    if ([[UIDevice currentDevice].systemVersion doubleValue]>=10.0) {
        [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"新版通知-注册成功-success");
            }else{
                NSLog(@"新版通知-注册失败-error");
            }
        }];
    }else if([[UIDevice currentDevice].systemVersion doubleValue]>=8.0){//8.0以后使用这种方法来注册推送通知
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else{
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    } 
    return YES;
}

3.收到本地通知后的处理逻辑

- (void)application:(UIApplication *)application didReceiveLocalNotification:(nonnull UILocalNotification *)notification{
    NSString *voiceString =nil;
    voiceString = [NSString stringWithFormat:@"语音播报:%@", notification.alertBody];
    [[CRSpeechManger sharedInstance] syntheticVoice:voiceString];
}

总结:本地推送较为简单,但要注意的是只有在前台时会调用didReceiveLocalNotification,后台状态时,只有用户点击后才能调用此方法。

远程通知
1.注册通知(和本地通知一样),用户同意后,会调用此程序,获取系统的deviceToken,应把deviceToken传给服务器保存,此函数会在程序每次启动时调用:

//registerForRemoteNotifications方法调用时机
//对于任何远程推送,registerForRemoteNotifications可以直接调用来注册远程推送,而不需要用户允许。也就是说只要调用-[UIApplication registerForRemoteNotifications],就可以在AppDelegate的application:didRegisterForRemoteNotificationsWithDeviceToken:中获取到设备的push token。
那么通常的弹窗询问权限有什么用呢?其实只是请求用户允许在推送通知到来时能够有alert, badge和sound,而并不是在请求注册推送本身的权限。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
}

2.收到消息的逻辑处理
ios10以后,需要实现[UNUserNotificationCenter currentNotificationCenter]的代理方法。

//用户点击通知栏,前后台处理方式一致,iOS 10以后是用户点击才回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler{
    //可按需求进行数据处理
    NSLog(@"%@",response);
}

// 下面处理iOS 10之后,设置前台收到远程消息时是否显示 当APP处于前台的时候接收到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSString *voiceString = [NSString stringWithFormat:@"语音播报:%@", notification.request.content.body];
    [[CRSpeechManger sharedInstance] syntheticVoice:voiceString];

}

iOS10以前通知回调方法,前台收到消息时调用,
后台模式下
普通推送:收到推送后(有文字有声音),点开通知,进入APP后,才执行
静默推送:收到推送(没有文字没有声音),不用点开通知,不用打开APP,就能执行,用户完全感觉不到,可以理解允许应用在收到通知后在后台运行一段代码,且能够马上执行

静默推送简介:静默推送(Silent Push)并不是必须要“静默”,只要推送payload中aps字典里包含了"content-available": 1的键值对,都具有静默推送的特性(比如唤醒应用),而无论你是否推了alert, badge或sound。则可以不打扰用户的情况下进行内容更新等操作。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    // 获取通知所带的数据
    //程序关闭状态点击推送消息打开
    NSLog(@"%@",userInfo[@"alert"]);
    //前台运行
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
       
    }
    //后台挂起时
    else{
      
    }
    //设置应用程序角标数为0
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSString *voiceString =nil;
    voiceString = [NSString stringWithFormat:@"语音播报:%@", userInfo[@"alert"]];
    [[CRSpeechManger sharedInstance] syntheticVoice:voiceString];
}

知识点梳理告一段落,下面讨论需求实现
我的想法是:
iOS 10之前的版本,采用静默推送,在实现播放固定的声音。

iOS 10之后,使用新增的UNNotificationServiceExtension
(mutable-content : 1),合成语音播报。

你可能感兴趣的:(iOS远程推送和本地推送总结)