| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- import Flutter
- import UIKit
- import BackgroundTasks
- import UserNotifications
- @main
- @objc class AppDelegate: FlutterAppDelegate {
- private var pushChannel: FlutterMethodChannel?
- private var notificationDelegate: UNUserNotificationCenterDelegate?
-
-
- override func application(
- _ application: UIApplication,
- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
- ) -> Bool {
- GeneratedPluginRegistrant.register(with: self)
- BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.shishi.dingwei.refresh", using: nil) { task in
- // 处理后台任务
- }
- ///设置推送
- setupPushNotifications();
-
- ///通知flutter打开了应用
- DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
- print("applicationDidFinishLaunchingWithOptionssfsdfsdfsd-f---");
- self?.pushChannel?.invokeMethod("applicationDidFinishLaunchingWithOptions", arguments: "")
- }
- return super.application(application, didFinishLaunchingWithOptions: launchOptions)
- }
-
- override func applicationDidEnterBackground(_ application: UIApplication) {
- pushChannel?.invokeMethod("applicationDidEnterBackground", arguments: "")
- }
-
- /// 设置推送通知
- func setupPushNotifications() {
- let controller = window?.rootViewController as! FlutterViewController
-
- // 创建推送通道
- pushChannel = FlutterMethodChannel(
- name: "com.example.app/push_notification",
- binaryMessenger: controller.binaryMessenger
- )
-
- // 设置方法调用处理
- pushChannel?.setMethodCallHandler { [weak self] call, result in
- switch call.method {
- case "getDeviceToken":
- self?.getDeviceToken(result: result)
- case "requestPermission":
- self?.requestNotificationPermission(result: result)
- default:
- result(FlutterMethodNotImplemented)
- }
- }
-
- // 创建单独的通知代理
- let delegate = NotificationDelegate(pushChannel: pushChannel!)
- UNUserNotificationCenter.current().delegate = delegate
- self.notificationDelegate = delegate
-
- // 请求推送权限
- UNUserNotificationCenter.current().requestAuthorization(
- options: [.alert, .sound, .badge]
- ) { granted, error in
- if granted {
- DispatchQueue.main.async {
- UIApplication.shared.registerForRemoteNotifications()
- }
- } else if let error = error {
- print("Error: \(error.localizedDescription)")
- }
- }
- }
-
-
- /// 获取设备令牌
- private func getDeviceToken(result: @escaping FlutterResult) {
- if let token = UserDefaults.standard.string(forKey: "deviceToken") {
- result(token)
- } else {
- result(nil)
- }
- }
-
- /// 请求推送权限
- private func requestNotificationPermission(result: @escaping FlutterResult) {
- UNUserNotificationCenter.current().requestAuthorization(
- options: [.alert, .sound, .badge]
- ) { granted, error in
- DispatchQueue.main.async {
- if let error = error {
- result(FlutterError(code: "notification_error", message: error.localizedDescription, details: nil))
- } else {
- result(granted)
- }
- }
- }
- }
-
- /// 处理接收到的推送令牌
- override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
- let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
- UserDefaults.standard.set(token, forKey: "deviceToken")
-
- // 将令牌发送到Flutter
- pushChannel?.invokeMethod("onTokenReceived", arguments: token)
- print("APNs token: \(token)")
- }
-
- /// 处理推送注册失败
- override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
- print("Failed to register for remote notifications: \(error.localizedDescription)")
- pushChannel?.invokeMethod("onTokenError", arguments: error.localizedDescription)
- }
- }
- // 单独的通知代理类
- class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
- private let pushChannel: FlutterMethodChannel
-
- init(pushChannel: FlutterMethodChannel) {
- self.pushChannel = pushChannel
- super.init()
- }
-
- func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
- let userInfo = notification.request.content.userInfo
- print("Foreground notification received: \(userInfo)")
-
- // 将通知内容发送到Flutter
- pushChannel.invokeMethod("onNotificationReceived", arguments: userInfo)
-
- // 显示通知
- completionHandler([.alert, .sound, .badge])
- }
-
- func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
- let userInfo = response.notification.request.content.userInfo
- print("Notification tapped: \(userInfo)")
-
- // 将点击事件发送到Flutter
- pushChannel.invokeMethod("onNotificationTapped", arguments: userInfo)
-
- completionHandler()
- }
- }
|