ios_push_notification_service.dart 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:get/get.dart';
  5. import 'package:get/get_core/src/get_main.dart';
  6. class IosPushNotificationService {
  7. static const MethodChannel _channel = MethodChannel('com.example.app/push_notification');
  8. // 回调函数
  9. static Function(String)? onTokenReceived;
  10. static Function(String)? onTokenError;
  11. static Function(Map<String, dynamic>)? onNotificationReceived;
  12. static Function(Map<String, dynamic>)? onNotificationTapped;
  13. // 初始化推送服务
  14. static void initialize() {
  15. _channel.setMethodCallHandler((call) async {
  16. switch (call.method) {
  17. case 'onTokenReceived':
  18. onTokenReceived?.call(call.arguments);
  19. break;
  20. case 'onTokenError':
  21. onTokenError?.call(call.arguments);
  22. break;
  23. case 'onNotificationReceived':
  24. if (call.arguments is Map) {
  25. onNotificationReceived?.call(Map<String, dynamic>.from(call.arguments));
  26. }
  27. break;
  28. case 'onNotificationTapped':
  29. if (call.arguments is Map) {
  30. onNotificationTapped?.call(Map<String, dynamic>.from(call.arguments));
  31. }
  32. break;
  33. default:
  34. throw PlatformException(
  35. code: 'UNIMPLEMENTED',
  36. message: 'Method not implemented',
  37. details: null,
  38. );
  39. }
  40. });
  41. }
  42. // 请求推送权限
  43. static Future<bool> requestPermission() async {
  44. try {
  45. final bool? granted = await _channel.invokeMethod('requestPermission');
  46. return granted ?? false;
  47. } on PlatformException catch (e) {
  48. print('Failed to request permission: ${e.message}');
  49. return false;
  50. }
  51. }
  52. // 获取设备令牌
  53. static Future<String?> getDeviceToken() async {
  54. try {
  55. final String? token = await _channel.invokeMethod('getDeviceToken');
  56. print("Strdefdjifjd---${token}");
  57. return token;
  58. } on PlatformException catch (e) {
  59. print('Failed to get device token: ${e.message}');
  60. return null;
  61. }
  62. }
  63. ///处理推送各种点击 skipType 0-首页 1-好友申请页面 2-好友消息页面
  64. static void handleNotificationPushChick(Map<String,dynamic> pushDict) {
  65. int skipType = pushDict["skipType"];
  66. // skipType = 0;
  67. // if (skipType == 0) {
  68. // Get.until((route) => route.isFirst);
  69. // // 在其他页面或组件中
  70. // final mainController = Get.find<MainController>();
  71. // // 调用方法
  72. // mainController.onTabClick(0); // 切换到第一个Tab
  73. // } else if (skipType == 1) {
  74. // MessagePage.start(initialIndex: 0);
  75. // } else if (skipType == 2) {
  76. // MessagePage.start(initialIndex: 1);
  77. // }
  78. }
  79. }