AppDelegate.swift 5.6 KB

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