AppDelegate.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import Flutter
  2. import UIKit
  3. import BackgroundTasks
  4. import UserNotifications
  5. @main
  6. @objc class AppDelegate: FlutterAppDelegate {
  7. private var pushChannel: FlutterMethodChannel?
  8. private var notificationDelegate: UNUserNotificationCenterDelegate?
  9. override func application(
  10. _ application: UIApplication,
  11. didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  12. ) -> Bool {
  13. GeneratedPluginRegistrant.register(with: self)
  14. BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.shishi.dingwei.refresh", using: nil) { task in
  15. // 处理后台任务
  16. }
  17. ///设置推送
  18. setupPushNotifications();
  19. return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  20. }
  21. /// 设置推送通知
  22. func setupPushNotifications() {
  23. let controller = window?.rootViewController as! FlutterViewController
  24. // 创建推送通道
  25. pushChannel = FlutterMethodChannel(
  26. name: "com.example.app/push_notification",
  27. binaryMessenger: controller.binaryMessenger
  28. )
  29. // 设置方法调用处理
  30. pushChannel?.setMethodCallHandler { [weak self] call, result in
  31. switch call.method {
  32. case "getDeviceToken":
  33. self?.getDeviceToken(result: result)
  34. case "requestPermission":
  35. self?.requestNotificationPermission(result: result)
  36. default:
  37. result(FlutterMethodNotImplemented)
  38. }
  39. }
  40. // 创建单独的通知代理
  41. let delegate = NotificationDelegate(pushChannel: pushChannel!)
  42. UNUserNotificationCenter.current().delegate = delegate
  43. self.notificationDelegate = delegate
  44. // 请求推送权限
  45. UNUserNotificationCenter.current().requestAuthorization(
  46. options: [.alert, .sound, .badge]
  47. ) { granted, error in
  48. if granted {
  49. DispatchQueue.main.async {
  50. UIApplication.shared.registerForRemoteNotifications()
  51. }
  52. } else if let error = error {
  53. print("Error: \(error.localizedDescription)")
  54. }
  55. }
  56. }
  57. /// 获取设备令牌
  58. private func getDeviceToken(result: @escaping FlutterResult) {
  59. if let token = UserDefaults.standard.string(forKey: "deviceToken") {
  60. result(token)
  61. } else {
  62. result(nil)
  63. }
  64. }
  65. /// 请求推送权限
  66. private func requestNotificationPermission(result: @escaping FlutterResult) {
  67. UNUserNotificationCenter.current().requestAuthorization(
  68. options: [.alert, .sound, .badge]
  69. ) { granted, error in
  70. DispatchQueue.main.async {
  71. if let error = error {
  72. result(FlutterError(code: "notification_error", message: error.localizedDescription, details: nil))
  73. } else {
  74. result(granted)
  75. }
  76. }
  77. }
  78. }
  79. /// 处理接收到的推送令牌
  80. override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  81. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  82. UserDefaults.standard.set(token, forKey: "deviceToken")
  83. // 将令牌发送到Flutter
  84. pushChannel?.invokeMethod("onTokenReceived", arguments: token)
  85. print("APNs token: \(token)")
  86. }
  87. /// 处理推送注册失败
  88. override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  89. print("Failed to register for remote notifications: \(error.localizedDescription)")
  90. pushChannel?.invokeMethod("onTokenError", arguments: error.localizedDescription)
  91. }
  92. }
  93. // 单独的通知代理类
  94. class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
  95. private let pushChannel: FlutterMethodChannel
  96. init(pushChannel: FlutterMethodChannel) {
  97. self.pushChannel = pushChannel
  98. super.init()
  99. }
  100. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  101. let userInfo = notification.request.content.userInfo
  102. print("Foreground notification received: \(userInfo)")
  103. // 将通知内容发送到Flutter
  104. pushChannel.invokeMethod("onNotificationReceived", arguments: userInfo)
  105. // 显示通知
  106. completionHandler([.alert, .sound, .badge])
  107. }
  108. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  109. let userInfo = response.notification.request.content.userInfo
  110. print("Notification tapped: \(userInfo)")
  111. // 将点击事件发送到Flutter
  112. pushChannel.invokeMethod("onNotificationTapped", arguments: userInfo)
  113. completionHandler()
  114. }
  115. }