文序
本文讲解是的是,flutter 如何添加推送能力,极光推送也有一个插件,但是好像无法实现点击推送,让APP 冷启动并并进入对应的业务子页面。
最好的办法就是自己去实现一下,一方面增加交互的理解,还可以加深记忆,总之能自己造轮子的自己造一个。
在这里,我们公司采用的友盟推送,其实逻辑都差不多的,下面我们进入正题。
一、flutter 部分的实现
- 推送首先肯定是原生接收到推送的消息,然后把消息传递给flutter
- 这里我们使用的是 原生与flutter通信通道的
EventChannel
,只需要给它添加推送的监听事件,即可。 - 在这里我们新建一个单独的类用来初始化
EventChannel
,my_eventchannel.dart,逻辑如下
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
typedef void EventChannelCallback(arg);
class MyEventChannel{
// 初始化一个广播流从channel中接收数据,返回的Stream调用listen方法完成注册,需要在页面销毁时调用Stream的cancel方法取消监听
StreamSubscription _streamSubscription;
static MyEventChannel _myEventChannel;
static instance(){
if(_myEventChannel==null){
_myEventChannel = MyEventChannel();
}
return _myEventChannel;
}
//这里一个回调函数,用来注册的使用给调用者使用的
void config(EventChannelCallback eventChannelCallback) {
_streamSubscription = EventChannel('EventChannel')
.receiveBroadcastStream()
.listen(eventChannelCallback, onError: _onToDartError);
}
void dispose() {
if (_streamSubscription != null) {
_streamSubscription.cancel();
_streamSubscription = null;
}
}
void _onToDartError(error) {
print("_onToDartError ===> " + error);
}
}
二、main.dart 调用者部分
- 首先是调用初始化
EventChannel
,这部分是比较简单的
@override
void initState() {
super.initState();
MyEventChannel myEventChannel = MyEventChannel.instance();
myEventChannel.config(receiveRemoteMsg);
}
//接收到的推送 ,根据自己的业务可以做对应的处理,我这里是页面跳转
void receiveRemoteMsg(msg) {
print("receiveRemoteMsg ===> " + msg);
if(msg == "1"){
Navigator.pushNamed(context, YJRouters.defeat_page);
}else if(msg=="3"){
Navigator.pushNamed(context, YJRouters.conflict_page);
}else if(msg=="2"||msg=="4"){
Navigator.pushNamed(context, YJRouters.follow_page);
}
}
三、原生的实现部分
- 首先就是用下xcode打开iOS工程,和以前集成推送一个样,pod 添加,然后初始化,实现推送的代理
这部分就不在重复了,就是首先要保证APP,可以收到推送 - 实现FlutterStreamHandler 代理方法
#pragma mark - <FlutterStreamHandler>
//这个onListen是Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(FlutterEventSink)eventSink {
// arguments flutter给native的参数
// 回调给flutter, 建议使用实例指向,因为该block可以使用多次
self.eventSink = eventSink;
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter给native的参数
self.eventSink = nil;
return nil;
}
//点击推送的时候,调用此方法,给flutter 发送消息
- (void)sendMessageByEventChannel:(NSString *)message{
if (self.eventSink) {
self.eventSink(message);
}
}
到这里基本上就算搞定了,但是点击推送的冷启动咋办,接下来
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//省略其他逻辑的代码....
NSLog(@"launchOptions==>%@",launchOptions);
if(launchOptions){
//这里就是点击推送冷启动APP,取出推送的消息,然后调用发送消息的法法
NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
NSLog(@"%@",userInfo);
NSString *page = [NSString stringWithFormat:@"%@",userInfo[@"type"]];
NSLog(@"type = %@",page);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self sendMessageByEventChannel:page];
});
}
}
- 到这里就完成了flutter实现友盟推送的所有逻辑。
附属AppDelegate.m 文件的所有代码
下面的我从我的项目文件中直接copy 过来的,仅供参考的,上面才是主要逻辑。
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "channels/NSString+AESEncrypt.h"
#import <UMPush/UMessage.h>
#import <UMCommon/UMCommon.h>
#import <Flutter/FlutterChannels.h>
static NSString *const kEventChannelName = @"EventChannel";
@interface AppDelegate ()<UIApplicationDelegate,UNUserNotificationCenterDelegate,FlutterStreamHandler>
@property(nonatomic,strong)FlutterEventChannel *eventChannel;
// FlutterEventSink:传输数据的载体
@property (nonatomic) FlutterEventSink eventSink;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
[self mychannel];
[self myeventchennel];
[self initUMcommon];
[self configUMPush:launchOptions];
NSLog(@"launchOptions==>%@",launchOptions);
if(launchOptions){
NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
NSLog(@"%@",userInfo);
NSString *page = [NSString stringWithFormat:@"%@",userInfo[@"type"]];
NSLog(@"type = %@",page);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self sendMessageByEventChannel:page];
});
}
//极光推送 注意最后一个参数
// [self startupJPush:launchOptions appKey:@"e47ec89f8da2b178864cb4ed" channel:@"AppStore" isProduction:NO];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
-(void)myeventchennel {
FlutterViewController *vc = (FlutterViewController *)self.window.rootViewController;
self.eventChannel = [FlutterEventChannel eventChannelWithName:kEventChannelName binaryMessenger:vc];
//设置消息处理器的代理
[self.eventChannel setStreamHandler:self];
}
#pragma mark----------------------------------FlutterStreamHandler
#pragma mark - <FlutterStreamHandler>
//这个onListen是Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(FlutterEventSink)eventSink {
// arguments flutter给native的参数
// 回调给flutter, 建议使用实例指向,因为该block可以使用多次
self.eventSink = eventSink;
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter给native的参数
self.eventSink = nil;
return nil;
}
- (void)sendMessageByEventChannel:(NSString *)message{
if (self.eventSink) {
self.eventSink(message);
}
}
#pragma mark----------------------------------mychannel
-(void)mychannel{
FlutterViewController *vc = (FlutterViewController *)self.window.rootViewController;
FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"sales_assist_channel" binaryMessenger:vc];
__weak typeof(self) weakself = self;
[channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
NSLog(@"%@",call);
if([call.method isEqualToString:@"getAesBCB"]){
NSDictionary *dic =(NSDictionary *)call.arguments;
NSString *pwd = dic[@"value"];
NSString *res = [pwd aci_encryptWithAES];
result(res);
}else if([call.method isEqualToString:@"AddTags"]){
NSDictionary *dic =(NSDictionary *)call.arguments;
NSString *pwd = dic[@"value"];
[weakself addTags:pwd];
result(pwd);
}else if([call.method isEqualToString:@"AddAdvisorAlias"]){
NSDictionary *dic =(NSDictionary *)call.arguments;
NSString *pwd = dic[@"value"];
[weakself addAlias:pwd];
result(pwd);
}else if([call.method isEqualToString:@"UMpusheLoginOut"]){
NSDictionary *dic =(NSDictionary *)call.arguments;
NSString *pwd = dic[@"value"];
// NSString *pwd2 = dic[@"value2"];
[weakself removeTags];
[weakself removeAlias:pwd];
result(pwd);
}
}];
}
#pragma mark----------------------------------友盟推送
-(void)initUMcommon {
[UMConfigure setEncryptEnabled:YES];//打开加密传输
[UMConfigure setLogEnabled:YES];//设置打开日志
[UMConfigure initWithAppkey:@"您申请的appkey" channel:@"App Store"];
}
-(void)configUMPush:(NSDictionary *)launchOptions{
// Push组件基本功能配置
UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
//type是对推送的几个参数的选择,可以选择一个或者多个。默认是三个全部打开,即:声音,弹窗,角标
entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
[UNUserNotificationCenter currentNotificationCenter].delegate=self;
[UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
}else{
}
}];
}
//iOS10以下使用这两个方法接收通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[UMessage setAutoAlert:NO];
if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
[UMessage didReceiveRemoteNotification:userInfo];
}
completionHandler(UIBackgroundFetchResultNewData);
}
//iOS10新增:处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
NSDictionary * userInfo = notification.request.content.userInfo;
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[UMessage setAutoAlert:NO];
//应用处于前台时的远程推送接受
//必须加这句代码
[UMessage didReceiveRemoteNotification:userInfo];
}else{
//应用处于前台时的本地推送接受
}
completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}
//iOS10新增:处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
NSDictionary * userInfo = response.notification.request.content.userInfo;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//应用处于后台时的远程推送接受
//必须加这句代码
[UMessage didReceiveRemoteNotification:userInfo];
NSLog(@"%@",userInfo);
NSString *page = [NSString stringWithFormat:@"%@",userInfo[@"type"]];
NSLog(@"type = %@",page);
[self sendMessageByEventChannel:page];
}else{
//应用处于后台时的本地推送接受
}
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
NSString *deviceTokenString2 = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"deviceTokenString2:%@", deviceTokenString2);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
NSLog(@"Regist fail%@",error);
}
-(void)addTags:(NSString *)comIDAndUserName{
[self removeTags];
//添加标签
[UMessage addTags:comIDAndUserName response:^(id _Nonnull responseObject, NSInteger remain, NSError * _Nonnull error) {
NSLog(@"添加标签");
NSLog(@"%@",responseObject);
NSLog(@"%@",error);
}];
}
-(void)removeTags{
//获取所有标签
[UMessage getTags:^(NSSet * _Nonnull responseTags, NSInteger remain, NSError * _Nonnull error) {
NSLog(@"responseTags==>%@",responseTags);
for(NSString *tag in responseTags){
//删除标签
[UMessage deleteTags:tag response:^(id _Nonnull responseObject, NSInteger remain, NSError * _Nonnull error) {
}];
}
}];
}
-(void)addAlias:(NSString *)comIDAndUserName{
//绑定别名
[UMessage addAlias:comIDAndUserName type:@"consultant" response:^(id _Nonnull responseObject, NSError * _Nonnull error) {
NSLog(@"绑定别名");
NSLog(@"%@",responseObject);
NSLog(@"%@",error);
}];
}
-(void)removeAlias:(NSString *)comIDAndUserName{
//移除别名
[UMessage removeAlias:comIDAndUserName type:@"consultant" response:^(id _Nonnull responseObject, NSError * _Nonnull error) {
NSLog(@"移除别名");
NSLog(@"%@",responseObject);
NSLog(@"%@",error);
}];
}
@end