Commit 46d70639 authored by xgz's avatar xgz

增加ios推送

parent 20412e03
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_jpush_vip/flutter_jpush_vip.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
FlutterJpushVip.init().then((value) {
print("============$value");
});
FlutterJpushVip.onNotification((n){
print("============$n");
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: GestureDetector(
onTap: () {
},
child: Center(
child: Text('Running on: test'),
)),
),
);
}
}
// import 'package:flutter/material.dart';
// import 'dart:async';
// import 'package:flutter/services.dart';
// import 'package:flutter_jpush_vip/flutter_jpush_vip.dart';
// void main() {
// runApp(MyApp());
// }
// class MyApp extends StatefulWidget {
// @override
// _MyAppState createState() => _MyAppState();
// }
// class _MyAppState extends State<MyApp> {
// @override
// void initState() {
// super.initState();
// FlutterJpushVip.init().then((value) {
// print("============$value");
// });
// FlutterJpushVip.onNotification((n){
// print("============$n");
// });
// }
// @override
// Widget build(BuildContext context) {
// return MaterialApp(
// home: Scaffold(
// appBar: AppBar(
// title: const Text('Plugin example app'),
// ),
// body: GestureDetector(
// onTap: () {
// },
// child: Center(
// child: Text('Running on: test'),
// )),
// ),
// );
// }
// }
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_jpush_vip_example/main.dart';
void main() {
testWidgets('Verify Platform version', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that platform version is retrieved.
expect(
find.byWidgetPredicate(
(Widget widget) => widget is Text &&
widget.data.startsWith('Running on:'),
),
findsOneWidget,
);
});
}
#import <Flutter/Flutter.h>
@interface FlutterJpushVipPlugin : NSObject<FlutterPlugin>
@property FlutterMethodChannel *channel;
+ (void)appdidLaunch:(NSDictionary*)launchOption;
@end
#import "FlutterJpushVipPlugin.h"
#if __has_include(<flutter_jpush_vip/flutter_jpush_vip-Swift.h>)
#import <flutter_jpush_vip/flutter_jpush_vip-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "flutter_jpush_vip-Swift.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <JPush/JPUSHService.h>
#define JPLog(fmt, ...) NSLog((@"| JPUSH | Flutter | iOS | " fmt), ##__VA_ARGS__)
@interface NSError (FlutterError)
@property(readonly, nonatomic) FlutterError *flutterError;
@end
@implementation NSError (FlutterError)
- (FlutterError *)flutterError {
return [FlutterError errorWithCode:[NSString stringWithFormat:@"Error %d", (int)self.code]
message:self.domain
details:self.localizedDescription];
}
@end
static NSMutableArray<FlutterResult>* getRidResults;
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@interface FlutterJpushVipPlugin ()<JPUSHRegisterDelegate>
@end
#endif
@implementation FlutterJpushVipPlugin
NSDictionary *_appLaunchNotification;
@implementation FlutterJpushVipPlugin{
NSDictionary *_launchNotification;
NSDictionary *_completeLaunchNotification;
BOOL _isJPushDidLogin;
JPAuthorizationOptions notificationTypes;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftFlutterJpushVipPlugin registerWithRegistrar:registrar];
getRidResults = @[].mutableCopy;
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"flutter_jpush_vip"
binaryMessenger:[registrar messenger]];
FlutterJpushVipPlugin* instance = [[FlutterJpushVipPlugin alloc] init];
instance.channel = channel;
[registrar addApplicationDelegate:instance];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (id)init {
self = [super init];
notificationTypes = 0;
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter removeObserver:self];
[defaultCenter addObserver:self
selector:@selector(networkConnecting:)
name:kJPFNetworkIsConnectingNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(networkRegister:)
name:kJPFNetworkDidRegisterNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(networkDidSetup:)
name:kJPFNetworkDidSetupNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(networkDidClose:)
name:kJPFNetworkDidCloseNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(networkDidLogin:)
name:kJPFNetworkDidLoginNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(networkDidReceiveMessage:)
name:kJPFNetworkDidReceiveMessageNotification
object:nil];
return self;
}
- (void)networkConnecting:(NSNotification *)notification {
_isJPushDidLogin = false;
}
- (void)networkRegister:(NSNotification *)notification {
_isJPushDidLogin = false;
}
- (void)networkDidSetup:(NSNotification *)notification {
_isJPushDidLogin = false;
}
- (void)networkDidClose:(NSNotification *)notification {
_isJPushDidLogin = false;
}
- (void)networkDidLogin:(NSNotification *)notification {
_isJPushDidLogin = YES;
for (FlutterResult result in getRidResults) {
result([JPUSHService registrationID]);
}
[getRidResults removeAllObjects];
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
[_channel invokeMethod:@"onReceiveMessage" arguments: [notification userInfo]];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"handleMethodCall:%@",call.method);
if ([@"getPlatformVersion" isEqualToString:call.method]) {
result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
} else if([@"init" isEqualToString:call.method]) {
[self setup:call result: result];
} else if([@"setTags" isEqualToString:call.method]) {
[self setTags:call result:result];
} else if([@"cleanTags" isEqualToString:call.method]) {
[self cleanTags:call result:result];
} else if([@"addTags" isEqualToString:call.method]) {
[self addTags:call result:result];
} else if([@"deleteTags" isEqualToString:call.method]) {
[self deleteTags:call result:result];
} else if([@"getAllTags" isEqualToString:call.method]) {
[self getAllTags:call result:result];
} else if([@"setAlias" isEqualToString:call.method]) {
[self setAlias:call result:result];
} else if([@"deleteAlias" isEqualToString:call.method]) {
[self deleteAlias:call result:result];
} else if([@"setBadge" isEqualToString:call.method]) {
[self setBadge:call result:result];
} else if([@"stopPush" isEqualToString:call.method]) {
[self stopPush:call result:result];
} else if([@"resumePush" isEqualToString:call.method]) {
JPLog(@"ios platform not support resume push.");
//[self applyPushAuthority:call result:result];
} else if([@"clearAllNotifications" isEqualToString:call.method]) {
[self clearAllNotifications:call result:result];
} else if ([@"clearNotification" isEqualToString:call.method]) {
[self clearNotification:call result:result];
} else if([@"getLaunchAppNotification" isEqualToString:call.method]) {
[self getLaunchAppNotification:call result:result];
} else if([@"getRegistrationID" isEqualToString:call.method]) {
[self getRegistrationID:call result:result];
} else if([@"sendLocalNotification"isEqualToString:call.method]) {
[self sendLocalNotification:call result:result];
} else if([@"isNotificationEnabled"isEqualToString:call.method]) {
[self isNotificationEnabled:call result:result];
} else if([@"openSettingsForNotification"isEqualToString:call.method]) {
[self openSettingsForNotification];
} else{
result(FlutterMethodNotImplemented);
}
}
- (void)setup:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"setup:");
NSDictionary *arguments = call.arguments;
NSNumber *debug = arguments[@"debug"];
if ([debug boolValue]) {
[JPUSHService setDebugMode];
} else {
[JPUSHService setLogOFF];
}
[JPUSHService setDebugMode];
// [JPUSHService setupWithOption:_completeLaunchNotification
// appKey:arguments[@"appKey"]
// channel:arguments[@"channel"]
// apsForProduction:[arguments[@"production"] boolValue]];
[JPUSHService setupWithOption:_completeLaunchNotification
appKey:@"07df3009b7469ad95427b4f7"
channel:@"00186a85d6e044ecce1406a8"
apsForProduction:[arguments[@"production"] boolValue]];
[self applyPushAuthority];
// _appLaunchNotification = @{@"UIApplicationLaunchOptionsRemoteNotificationKey":@{
// @"_j_business": @(1),
// @"_j_msgid" : @"20266327955950814",
// @"_j_uid" : @"50921634995",
// @"android_redirect_url" : @"https://h5cdn.xiaomanxiong.com/activity_h5/h5_transit_page.html?identifying=169&platform=wph",
// @"aps": @{
// @"alert": @{
// @"body" : @"test",
// @"title" : @"test"
// },
// @"badge" :@(1)
// },
// @"ios_redirect_url" : @"https://h5cdn.xiaomanxiong.com/activity_h5/h5_transit_page.html?identifying=169&platform=wph",
// @"redirect_type" : @(1)
// }};
if(_appLaunchNotification != nil){
[self jpushFlutterFormatAPNSDic1:_appLaunchNotification];
_appLaunchNotification = nil;
}
result(@{@"code":[NSNumber numberWithInt:0],@"registrationId":[JPUSHService registrationID]});
}
+ (void)appdidLaunch:(NSDictionary*)launchOption{
_appLaunchNotification = launchOption;
}
- (void)applyPushAuthority{
notificationTypes = 0;
notificationTypes |= JPAuthorizationOptionSound;
notificationTypes |= JPAuthorizationOptionAlert;
notificationTypes |= JPAuthorizationOptionBadge;
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = notificationTypes;
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}
- (void)setTags:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"setTags:%@",call.arguments);
NSSet *tagSet;
if (call.arguments != NULL) {
tagSet = [NSSet setWithArray: call.arguments];
}
[JPUSHService setTags:tagSet completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode == 0) {
result(@{@"tags": [iTags allObjects] ?: @[]});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)cleanTags:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"cleanTags:");
[JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode == 0) {
result(@{@"tags": iTags ? [iTags allObjects] : @[]});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)addTags:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"addTags:%@",call.arguments);
NSSet *tagSet;
if (call.arguments != NULL) {
tagSet = [NSSet setWithArray:call.arguments];
}
[JPUSHService addTags:tagSet completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode == 0) {
result(@{@"tags": [iTags allObjects] ?: @[]});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)deleteTags:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"deleteTags:%@",call.arguments);
NSSet *tagSet;
if (call.arguments != NULL) {
tagSet = [NSSet setWithArray:call.arguments];
}
[JPUSHService deleteTags:tagSet completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode == 0) {
result(@{@"tags": [iTags allObjects] ?: @[]});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)getAllTags:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"getAllTags:");
[JPUSHService getAllTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode == 0) {
result(@{@"tags": iTags ? [iTags allObjects] : @[]});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)setAlias:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"setAlias:%@",call.arguments);
NSString *alias = call.arguments;
[JPUSHService setAlias:alias completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
if (iResCode == 0) {
result(@{@"alias": iAlias ?: @""});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)deleteAlias:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"deleteAlias:%@",call.arguments);
[JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
if (iResCode == 0) {
result(@{@"alias": iAlias ?: @""});
} else {
NSError *error = [[NSError alloc] initWithDomain:@"JPush.Flutter" code:iResCode userInfo:nil];
result([error flutterError]);
}
} seq: 0];
}
- (void)setBadge:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"setBadge:%@",call.arguments);
NSInteger badge = [call.arguments[@"badge"] integerValue];
if (badge < 0) {
badge = 0;
}
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: badge];
[JPUSHService setBadge: badge];
}
- (void)stopPush:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"stopPush:");
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
}
- (void)clearAllNotifications:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"clearAllNotifications:");
if (@available(iOS 10.0, *)) {
//iOS 10 以上支持
JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
identifier.identifiers = nil;
identifier.delivered = YES; //等于 YES 则移除所有在通知中心显示的,等于 NO 则为移除所有待推送的
[JPUSHService removeNotification:identifier];
} else {
// iOS 10 以下移除所有推送;iOS 10 以上移除所有在通知中心显示推送和待推送请求
[JPUSHService removeNotification:nil];
}
}
- (void)clearNotification:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"clearNotification:");
NSNumber *notificationId = call.arguments;
if (!notificationId) {
return ;
}
JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
identifier.identifiers = @[notificationId.stringValue];
if (@available(iOS 10.0, *)) {
//iOS 10 以上有效,等于 YES 则在通知中心显示的里面移除,等于 NO 则为在待推送的里面移除;iOS 10 以下无效
identifier.delivered = YES;
} else {
// Fallback on earlier versions
}
[JPUSHService removeNotification:identifier];
}
- (void)getLaunchAppNotification:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"getLaunchAppNotification");
result(_launchNotification == nil ? @{}: _launchNotification);
}
- (void)getRegistrationID:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"getRegistrationID:");
#if TARGET_IPHONE_SIMULATOR//模拟器
NSLog(@"simulator can not get registrationid");
result(@"");
#elif TARGET_OS_IPHONE//真机
if ([JPUSHService registrationID] != nil && ![[JPUSHService registrationID] isEqualToString:@""]) {
// 如果已经成功获取 registrationID,从本地获取直接缓存
result([JPUSHService registrationID]);
return;
}
if (_isJPushDidLogin) {// 第一次获取未登录情况
result(@[[JPUSHService registrationID]]);
} else {
[getRidResults addObject:result];
}
#endif
}
- (void)sendLocalNotification:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"sendLocalNotification:%@",call.arguments);
JPushNotificationContent *content = [[JPushNotificationContent alloc] init];
NSDictionary *params = call.arguments;
if (params[@"title"]) {
content.title = params[@"title"];
}
if (params[@"subtitle"] && ![params[@"subtitle"] isEqualToString:@"<null>"]) {
content.subtitle = params[@"subtitle"];
}
if (params[@"content"]) {
content.body = params[@"content"];
}
if (params[@"badge"]) {
content.badge = params[@"badge"];
}
if (params[@"action"] && ![params[@"action"] isEqualToString:@"<null>"]) {
content.action = params[@"action"];
}
if ([params[@"extra"] isKindOfClass:[NSDictionary class]]) {
content.userInfo = params[@"extra"];
}
if (params[@"sound"] && ![params[@"sound"] isEqualToString:@"<null>"]) {
content.sound = params[@"sound"];
}
JPushNotificationTrigger *trigger = [[JPushNotificationTrigger alloc] init];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
if (params[@"fireTime"]) {
NSNumber *date = params[@"fireTime"];
NSTimeInterval currentInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval interval = [date doubleValue]/1000 - currentInterval;
interval = interval>0?interval:0;
trigger.timeInterval = interval;
}
}
else {
if (params[@"fireTime"]) {
NSNumber *date = params[@"fireTime"];
trigger.fireDate = [NSDate dateWithTimeIntervalSince1970: [date doubleValue]/1000];
}
}
JPushNotificationRequest *request = [[JPushNotificationRequest alloc] init];
request.content = content;
request.trigger = trigger;
if (params[@"id"]) {
NSNumber *identify = params[@"id"];
request.requestIdentifier = [identify stringValue];
}
request.completionHandler = ^(id result) {
NSLog(@"result");
};
[JPUSHService addNotification:request];
result(@[@[]]);
}
/// 检查当前应用的通知开关是否开启
- (void)isNotificationEnabled:(FlutterMethodCall*)call result:(FlutterResult)result {
JPLog(@"isNotificationEnabled:");
[JPUSHService requestNotificationAuthorization:^(JPAuthorizationStatus status) {
BOOL isEnabled = NO;
if (status == JPAuthorizationStatusAuthorized) {
isEnabled = YES;
}
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:isEnabled],@"isEnabled", nil];
dispatch_async(dispatch_get_main_queue(), ^{
result(dict);
});
}];
}
- (void)openSettingsForNotification {
JPLog(@"openSettingsForNotification:");
[JPUSHService openSettingsForNotification:^(BOOL success) {
JPLog(@"openSettingsForNotification: %@",@(success));
}];
}
- (void)dealloc {
_isJPushDidLogin = NO;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_completeLaunchNotification = launchOptions;
if (launchOptions != nil) {
_launchNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
_launchNotification = [self jpushFormatAPNSDic:_launchNotification.copy];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:[NSString stringWithFormat:@"%@",launchOptions] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"title" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:true completion:nil];
}
if ([launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSMutableDictionary *localNotificationEvent = @{}.mutableCopy;
localNotificationEvent[@"content"] = localNotification.alertBody;
localNotificationEvent[@"badge"] = @(localNotification.applicationIconBadgeNumber);
localNotificationEvent[@"extras"] = localNotification.userInfo;
localNotificationEvent[@"fireTime"] = [NSNumber numberWithLong:[localNotification.fireDate timeIntervalSince1970] * 1000];
localNotificationEvent[@"soundName"] = [localNotification.soundName isEqualToString:UILocalNotificationDefaultSoundName] ? @"" : localNotification.soundName;
// localNotificationEvent[@"msg_id"] = [NSString stringWithFormat:@"%@",dic[@"_j_msgid"]];
// localNotificationEvent[@"n_content"] = dic[@"aps"][@"alert"][@"body"];
// localNotificationEvent[@"n_title"] = dic[@"aps"][@"alert"][@"title"];
// localNotificationEvent[@"n_extras"] = [self jpushFormatAPNSDic:dic][@"extras"];
if (@available(iOS 8.2, *)) {
localNotificationEvent[@"title"] = localNotification.alertTitle;
}
_launchNotification = localNotificationEvent;
}
// [self performSelector:@selector(addNotificationWithDateTrigger) withObject:nil afterDelay:2];
return YES;
}
- (void)addNotificationWithDateTrigger:(NSDictionary *)dic {
// JPushNotificationTrigger *trigger = [[JPushNotificationTrigger alloc] init];
//
// if (@available(iOS 10.0, *)) {
// trigger.timeInterval = 10;
// } else {
// NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
// trigger.fireDate = fireDate;
// }
//
// JPushNotificationContent *content = [[JPushNotificationContent alloc] init];
// content.title = @"title";
// content.subtitle = @"subtitle";
// content.body = @"body";
// content.badge = @(1);
// content.action = @"action";
// content.categoryIdentifier = @"categoryIdentifier";
// content.threadIdentifier = @"threadIdentifier";
//
// JPushNotificationRequest *request = [[JPushNotificationRequest alloc] init];
// request.content = content;
// request.trigger = trigger;
// request.completionHandler = ^(id result) {
// // iOS10以上成功则result为UNNotificationRequest对象,失败则result为nil
// // iOS10以下成功result为UILocalNotification对象,失败则result为nil
// if (result) {
// NSLog(@"添加日期通知成功 --- %@", result);
// }
// };
// request.requestIdentifier = @"123";
// [JPUSHService addNotification:request];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// _resumingFromBackground = YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// application.applicationIconBadgeNumber = 1;
// application.applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
NSDictionary *settingsDictionary = @{
@"sound" : [NSNumber numberWithBool:notificationSettings.types & UIUserNotificationTypeSound],
@"badge" : [NSNumber numberWithBool:notificationSettings.types & UIUserNotificationTypeBadge],
@"alert" : [NSNumber numberWithBool:notificationSettings.types & UIUserNotificationTypeAlert],
};
[_channel invokeMethod:@"onIosSettingsRegistered" arguments:settingsDictionary];
}
- (BOOL)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
JPLog(@"application:didReceiveRemoteNotification:fetchCompletionHandler");
[JPUSHService handleRemoteNotification:userInfo];
[_channel invokeMethod:@"onReceiveNotification" arguments:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
return YES;
}
// iOS 10 以下点击本地通知
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
JPLog(@"application:didReceiveLocalNotification:");
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
NSString *title = @"";
if (@available(iOS 8.2, *)) {
title = notification.alertTitle;
} else {
// Fallback on earlier versions
}
NSString *body = notification.alertBody;
NSString *action = notification.alertAction;
[dic setValue:title?:@"" forKey:@"title"];
[dic setValue:body?:@"" forKey:@"body"];
[dic setValue:action?:@"" forKey:@"action"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.channel invokeMethod:@"onOpenNotification" arguments:dic];
});
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler API_AVAILABLE(ios(10.0)){
JPLog(@"jpushNotificationCenter:willPresentNotification::");
NSDictionary * userInfo = notification.request.content.userInfo;
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[_channel invokeMethod:@"onReceiveNotification" arguments: [self jpushFormatAPNSDic:userInfo]];
}else{
JPLog(@"iOS10 前台收到本地通知:userInfo:%@",userInfo);
}
completionHandler(notificationTypes);
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler API_AVAILABLE(ios(10.0)){
JPLog(@"jpushNotificationCenter:didReceiveNotificationResponse::");
NSDictionary * userInfo = response.notification.request.content.userInfo;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
// [_channel invokeMethod:@"onOpenNotification" arguments: [self jpushFormatAPNSDic:userInfo]];
[_channel invokeMethod:@"__JPUSH_MESSAGE__" arguments: [self jpushFlutterFormatAPNSDic:userInfo]];
}else{
// iOS 10 以上点击本地通知
JPLog(@"iOS10 点击本地通知");
dispatch_async(dispatch_get_main_queue(), ^{
[self.channel invokeMethod:@"__JPUSH_MESSAGE__" arguments:[self jpushFlutterFormatAPNSDic:userInfo]];
});
}
completionHandler();
}
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
JPLog(@"");
BOOL isEnabled = NO;
if (status == JPAuthorizationStatusAuthorized) {
isEnabled = YES;
}
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:isEnabled],@"isEnabled", nil];
__weak typeof(self) weakself = self;
dispatch_async(dispatch_get_main_queue(), ^{
__strong typeof(self) strongself = weakself;
[strongself.channel invokeMethod:@"onReceiveNotificationAuthorization" arguments: dict];
});
}
- (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;
}
- (NSMutableDictionary *)jpushFlutterFormatAPNSDic:(NSDictionary *)dic {
NSMutableDictionary *formatDic = [NSMutableDictionary dictionary];
formatDic[@"msg_id"] = [NSString stringWithFormat:@"%@",dic[@"_j_msgid"]];
formatDic[@"n_content"] = dic[@"aps"][@"alert"][@"body"];
formatDic[@"n_title"] = dic[@"aps"][@"alert"][@"title"];
formatDic[@"n_extras"] = [self jpushFormatAPNSDic:dic][@"extras"];
return formatDic;
}
- (void)jpushFlutterFormatAPNSDic1:(NSDictionary *)launchOptions {
// UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:[NSString stringWithFormat:@"%@",@"ssss"] preferredStyle:UIAlertControllerStyleAlert];
// UIAlertAction *action = [UIAlertAction actionWithTitle:@"title" style:UIAlertActionStyleDefault handler:nil];
// [alert addAction:action];
// [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:true completion:nil];
if (launchOptions != nil) {
// _launchNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
NSMutableDictionary *localNotificationEvent = @{}.mutableCopy;
NSDictionary *localNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
localNotificationEvent[@"msg_id"] = [NSString stringWithFormat:@"%@",localNotification[@"_j_msgid"]];
localNotificationEvent[@"n_content"] = localNotification[@"aps"][@"alert"][@"body"];
localNotificationEvent[@"n_title"] = localNotification[@"aps"][@"alert"][@"title"];
localNotificationEvent[@"n_extras"] = [self jpushFormatAPNSDic:localNotification][@"extras"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[_channel invokeMethod:@"__JPUSH_MESSAGE__" arguments: localNotificationEvent];
});
// UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:[NSString stringWithFormat:@"%@",localNotification] preferredStyle:UIAlertControllerStyleAlert];
// UIAlertAction *action = [UIAlertAction actionWithTitle:@"title" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// [_channel invokeMethod:@"__JPUSH_MESSAGE__" arguments: localNotificationEvent];
// }];
// [alert addAction:action];
// [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:true completion:nil];
// _launchNotification = localNotificationEvent;
}
if ([launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
// UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// NSMutableDictionary *localNotificationEvent = @{}.mutableCopy;
//
//
// NSDictionary *dic =localNotification.userInfo;
// localNotificationEvent[@"msg_id"] = [NSString stringWithFormat:@"%@",dic[@"_j_msgid"]];
// localNotificationEvent[@"n_content"] = dic[@"aps"][@"alert"][@"body"];
// localNotificationEvent[@"n_title"] = dic[@"aps"][@"alert"][@"title"];
// localNotificationEvent[@"n_extras"] = [self jpushFormatAPNSDic:dic][@"extras"];
//
// if (@available(iOS 8.2, *)) {
// localNotificationEvent[@"title"] = localNotification.alertTitle;
// }
// _launchNotification = localNotificationEvent;
// [_channel invokeMethod:@"__JPUSH_MESSAGE__" arguments: localNotificationEvent];
}
}
@end
import Flutter
import UIKit
public class SwiftFlutterJpushVipPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_jpush_vip", binaryMessenger: registrar.messenger())
let instance = SwiftFlutterJpushVipPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
result("iOS " + UIDevice.current.systemVersion)
}
}
......@@ -16,6 +16,11 @@ Pod::Spec.new do |s|
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
s.dependency 'JCore','2.4.0'
s.dependency 'JPush','3.4.0'
s.ios.deployment_target = '10.0'
s.static_framework = true
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
......
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
class FlutterJpushVip {
static const MethodChannel _channel =
const MethodChannel('flutter_jpush_vip');
/// 初始化
static Future<_InitResult> init() async {
var map = await _channel.invokeMethod('init');
/// [production] ios only 生产环境
static Future<_InitResult> init({bool production = true}) async {
var map = await _channel.invokeMethod('init', {'production': production});
return _InitResult.from(map);
}
///
/// iOS Only
/// 申请推送权限,注意这个方法只会向用户弹出一次推送权限请求(如果用户不同意,之后只能用户到设置页面里面勾选相应权限),需要开发者选择合适的时机调用。
///
void applyPushAuthority(
[NotificationSettingsIOS iosSettings = const NotificationSettingsIOS()]) {
if (!Platform.isIOS) {
return;
}
_channel.invokeMethod('applyPushAuthority', iosSettings.toMap());
}
/// 开启调试模式
static void debug() {
_channel.invokeMethod('debug');
}
/// 获取注册ID
static Future<String> getRegistrationID() {
return _channel.invokeMethod('getRegistrationID');
}
/// 清除通知
static void clearAllNotifications() {
_channel.invokeMethod('clearAllNotifications');
}
/// 监听通知
static void onNotification(Function(_Notification notification) callback) {
_channel.setMethodCallHandler((call) {
if (call.method == '__JPUSH_MESSAGE__') {
try {
Map map = json.decode(call.arguments);
Map map = call.arguments;
if (call.arguments.runtimeType.toString().contains('String')) {
map = json.decode(call.arguments);
}
var n = _Notification.from(map);
callback(n);
} catch (e) {
......@@ -70,3 +92,19 @@ class _Notification {
return 'Notification{msgId: $msgId, content: $content, title: $title, extras: $extras, platform: $platform}';
}
}
class NotificationSettingsIOS {
final bool sound;
final bool alert;
final bool badge;
const NotificationSettingsIOS({
this.sound = true,
this.alert = true,
this.badge = true,
});
Map<String, dynamic> toMap() {
return <String, bool>{'sound': sound, 'alert': alert, 'badge': badge};
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment