iOS Development

ios – Flutter customized sound native notification not working

Spread the love


I wish to change the notification sound with the native notification bundle in flutter, it really works fantastic on the android facet however there’s a downside on the iOS facet

no downside when i ship this physique to this hyperlink https://fcm.googleapis.com/fcm/ship with postman i can hear the notification sound I need

{
    "to" : "My system Id",
    "notification" : {
        "title" : "Sound take a look at",
        "physique" : "Sound physique",
        "sound" : "sound.wav"
    }
}

however once I wish to get this sound in all notifications, the notification comes however I do not hear any sound.
That is my full code

class NotificationServices {
  CustomerViewModel customerViewModel = CustomerViewModel();
  //initialising firebase message plugin
  FirebaseMessaging messaging = FirebaseMessaging.occasion;

  //initialising firebase message plugin
  last FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  //perform to initialise flutter native notification plugin to indicate notifications for android when app is lively
  void initLocalNotifications(
      BuildContext context, RemoteMessage message) async {
    var androidInitializationSettings =
        const AndroidInitializationSettings('@drawable/ic_launcher');
    var iosInitializationSettings = const DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );

    var initializationSetting = InitializationSettings(
        android: androidInitializationSettings, iOS: iosInitializationSettings);

    await _flutterLocalNotificationsPlugin.initialize(initializationSetting,
        onDidReceiveNotificationResponse: (payload) {
      // deal with interplay when app is lively for android
      handleMessage(context, message);
    });
  }

  void firebaseInit(BuildContext context) {
    FirebaseMessaging.onMessage.hear((message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification!.android;

      if (kDebugMode) {
        print("notifications title:${notification!.title}");
        print("notifications physique:${notification.physique}");
        print('rely:${android!.rely}');
        print('knowledge:${message.knowledge.toString()}');
      }

      if (Platform.isIOS) {
        forgroundMessage();
      }

      if (Platform.isAndroid) {
        initLocalNotifications(context, message);
        showNotification(message);
      }
    });
  }

  void requestNotificationPermission() async {
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: true,
      criticalAlert: true,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.approved) {
      if (kDebugMode) {
        print('person granted permission');
      }
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
      if (kDebugMode) {
        print('person granted provisional permission');
      }
    } else {
      if (kDebugMode) {
        print('person denied permission');
      }
    }
  }

  // perform to indicate seen notification when app is lively
  Future<void> showNotification(RemoteMessage message) async {
    AndroidNotificationChannel channel = AndroidNotificationChannel(
        message.notification!.android!.channelId.toString(),
        message.notification!.android!.channelId.toString(),
        significance: Significance.max,
        showBadge: true,
        playSound: true,
        sound: const RawResourceAndroidNotificationSound('notification'));

    AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'bana_lazimsin_channel', 'Excessive Significance Notifications',
            channelDescription:
                'This channel is used for necessary notifications',
            significance: Significance.excessive,
            precedence: Precedence.excessive,
            playSound: true,
            ticker: 'ticker',
            icon: '@drawable/ic_launcher',
            shade: const Shade.fromARGB(255, 255, 15, 123),
            sound: channel.sound);
    DarwinNotificationDetails darwinNotificationDetails =
        const DarwinNotificationDetails(sound: 'notification.wav'
            // presentAlert: true,
            // presentBadge: true,
            // presentSound: true,
            );

    NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails, iOS: darwinNotificationDetails);

    Future.delayed(Length.zero, () {
      _flutterLocalNotificationsPlugin.present(
        0,
        message.notification!.title.toString(),
        message.notification!.physique.toString(),
        notificationDetails,
      );
    });
  }

  //perform to get system token on which we'll ship the notifications
  Future<String> getDeviceToken() async {
    String? token = await messaging.getToken();
    return token!;
  }

  void isTokenRefresh() async {
    messaging.onTokenRefresh.hear((occasion) {
      occasion.toString();
      if (kDebugMode) {
        print('refresh');
      }
    });
  }

  //deal with faucet on notification when app is in background or terminated
  Future<void> setupInteractMessage(BuildContext context) async {
    // when app is terminated
    RemoteMessage? initialMessage =
        await FirebaseMessaging.occasion.getInitialMessage();

    if (initialMessage != null) {
      handleMessage(context, initialMessage);
    }

    //when app ins background
    FirebaseMessaging.onMessageOpenedApp.hear((occasion) {
      handleMessage(context, occasion);
    });
  }

  void handleMessage(BuildContext context, RemoteMessage message) async {
    if (message.knowledge['type'] == 'message') {
      String customerId = message.knowledge['customerId'];
      Buyer? buyer =
          await customerViewModel.fetchOtherCustomer(customerId);
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => ChatPage(buyer: buyer!)));
    } else if (message.knowledge['type'] == 'Job') {
      String jobId = message.knowledge['itemId'];
      int parsedJobId = int.parse(jobId);
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => UserJobDetailPage(
                    jobId: parsedJobId,
                  )));
    } else if (message.knowledge['type'] == 'JobOffer') {
      String jobId = message.knowledge['itemId'];
      int parsedJobId = int.parse(jobId);
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => JobOfferDetailPage(
                    jobId: parsedJobId,
                    isActive: true,
                  )));
    } else if (message.knowledge['type'] == 'NewJob') {
      Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const MainPage(
              isBidder: true,
            ),
          ));
    } else {}
  }

  Future forgroundMessage() async {
    await FirebaseMessaging.occasion
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }
}

If (Platform.isIOS) { in firebaseInit perform
        forgroundMessage();
      } 

half I feel it solely runs the forgroundMessage half with out working different capabilities associated to iOS and finishes

and my major.dart file

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
}

void major() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colours.clear));
  runApp(const MyApp());
}

and the half the place I name them in initState on the main_page of my software

 @override
  void initState() {
    loginViewModel = Supplier.of<LoginViewModel>(context, hear: false);
    notificationServices.requestNotificationPermission();
    notificationServices.forgroundMessage();
    notificationServices.firebaseInit(context);
    notificationServices.setupInteractMessage(context);
    notificationServices.isTokenRefresh();

    notificationServices.getDeviceToken().then((worth) {
      if (kDebugMode) {
        print('system token');
        print(worth);
      }
    });
    upBody = widget.isBidder ? const HomePageForBidder() : const HomePage();

    for (var tab in tabIconsList) {
      tab.isSelected = false;
    }
    tabIconsList[0].isSelected = true;

    animationController = AnimationController(
        period: const Length(milliseconds: 600), vsync: this);

    tremendous.initState();
  }

Leave a Reply

Your email address will not be published. Required fields are marked *