自定义iOS通知声音本地通知包Flutter

y0u0uwnf  于 2023-01-05  发布在  Flutter
关注(0)|答案(1)|浏览(210)

我使用Firebase Cloud Messaging向flutter应用发送通知,并使用flutter_local_notifications包来处理这些通知,但当我尝试更改默认通知声音时,它在Android上有效,但在iOS上无效。请记住,我将“sound.aiff”添加到了原生iOS项目的根目录中,有人能告诉我这里遗漏了什么吗?在此提前表示感谢

class FCMFunctions {
  static final FCMFunctions _singleton = new FCMFunctions._internal();

  FCMFunctions._internal();

  factory FCMFunctions() {
    return _singleton;
  }

  late FirebaseMessaging messaging;

//************************************************************************************************************ */
  /// Create a [AndroidNotificationChannel] for heads up notifications
  late AndroidNotificationChannel channel;

  /// Initialize the [FlutterLocalNotificationsPlugin] package.
  late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

//************************************************************************************************************ */

  Future initApp() async {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );

    messaging = FirebaseMessaging.instance;

    if (!kIsWeb) {
      channel = const AndroidNotificationChannel(
        'high_importance_channel', // id
        'High Importance Notifications', // title
        importance: Importance.high,
        sound: RawResourceAndroidNotificationSound('sound'),
        playSound: true,
      );

      flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

      /// Create an Android Notification Channel.
      ///
      /// We use this channel in the `AndroidManifest.xml` file to override the
      /// default FCM channel to enable heads up notifications.
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()
          ?.createNotificationChannel(channel);

      //for IOS Foreground Notification
      await messaging.setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
      );
    }
  }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  void initializeNotifications() async {
    var initializationSettingsAndroid =
        const AndroidInitializationSettings('icon');
    var initializationSettingsIOS = const IOSInitializationSettings();
    //var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onSelectNotification: onSelectNotification,
    );
  }

  Future onSelectNotification(String? payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
    }
    navigatorKey.currentState!.pushNamed(Routes.blackCurrency,
        arguments: false); //message.data['category']
  }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  Future subscripeToTopics(String topic) async {
    await messaging.subscribeToTopic(topic);
  }

  ///Expire : https://firebase.google.com/docs/cloud-messaging/manage-tokens
  Future<String?> getFCMToken() async {
    final fcmToken = await messaging.getToken();
    return fcmToken;
  }

  void tokenListener() {
    messaging.onTokenRefresh.listen((fcmToken) {
      print("FCM Token dinlemede");
      // TODO: If necessary send token to application server.
    }).onError((err) {
      print(err);
    });
  }

  /// IOS
  Future iosWebPermission() async {
    if (Platform.isIOS || kIsWeb) {
      NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
        sound: true,
      );
    }
  }

  ///Foreground messages
  ///
  ///To handle messages while your application is in the foreground, listen to the onMessage stream.
  void foreGroundMessageListener() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print(
          '///////////////////////////// NOTIFICATIONS ARE COMMING /////////////////////////////');
      print('${message.notification!.body} ');
      print("Message data type : ${message.data.runtimeType}");

      var bodyRaw = message.data['body'];
      var body = List<dynamic>.from(jsonDecode(bodyRaw ?? '[]'));
      print("body : $body");

      String bodyMessage = '';
      if (body.first['sale'] == null) {
        bodyMessage = body.first['name'];
      } else if (body.first['name'] == null) {
        bodyMessage = body.first['sale'];
      } else {
        bodyMessage =
            body.map((e) => e['name'] + '-' + e['sale']).join(',  ').toString();
      }

      RemoteNotification? notification = RemoteNotification(
        android: const AndroidNotification(
          smallIcon: 'assets/imgs/logo.png',
          priority: AndroidNotificationPriority.highPriority,
          visibility: AndroidNotificationVisibility.public,
        ),
        apple: const AppleNotification(
          sound: AppleNotificationSound(
            name: 'sound',
          volume: 1.0,
          ),

        ),
        title: message.data['title'],
        body: bodyMessage,
      );
      // message.notification;
      AndroidNotification? android =
          notification.android; //message.notification?.android;
      if (notification != null && android != null && !kIsWeb) {
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channelDescription: channel.description,
              importance: Importance.max,
              priority: Priority.max,
              ticker: 'ticker',
              sound: const RawResourceAndroidNotificationSound('sound'),
              //   icon: "@mipmap/icon",
              playSound: true,
              styleInformation: const DefaultStyleInformation(true, true),
            ),
            iOS: const IOSNotificationDetails(
              presentAlert: true,
              presentBadge: true,
              presentSound: true,
              sound: 'sound',
            ),
          ),
        );
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
      navigatorKey.currentState!.pushNamed(Routes.blackCurrency,
          arguments: false); //message.data['category']

      //  Navigator.pushNamed(
      //    context,
      //    '/message',
      //    arguments: MessageArguments(message, true),
      //  );
    });
  }
}

final fcmFunctions = FCMFunctions();
cgyqldqp

cgyqldqp1#

您的服务器管理员将发送给您的声音名称在通知负载,您添加到iOS文件夹。负载将如下所示

{
    aps =     
    {
        alert = "notification message";
        sound = "example.caf";
    };
}

更多信息检查此参考link

相关问题