AppDelegate.swift 5.5 KB

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