Skip to content

[firebase_messaging] onLaunch & onResume not working on iOS but on Android work #2647

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
febryituery opened this issue May 27, 2020 · 1 comment

Comments

@febryituery
Copy link

febryituery commented May 27, 2020

Describe the bug
Hi, i found some problem when using this plugin for iOS, especialy when receiving notification onLaunch & onResume. on iOS, receiving notification onMessage only work when app is foreground and notification always show whenever app is open (always show up like that whenever i try to test notification from background). i tested on android and it work perfectly with no problem. and also, i'm using flutter_local_notification for showing local notification.

To Reproduce
Steps to reproduce the behavior:

  1. Using firebase_messaging: ^6.0.16
  2. Using flutter_local_notifications: ^1.4.3
  3. main.dart
import 'dart:async';
import 'dart:io' show Platform;
import 'dart:typed_data';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_crashlytics/flutter_crashlytics.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:****/constant/static_constant.dart';
import 'package:****/screen/splash/splash_view.dart';
import 'package:****/util/notification_service.dart';
import 'package:rxdart/subjects.dart';

final BehaviorSubject<String> selectNotificationSubject = BehaviorSubject<String>();
final BehaviorSubject<ReceivedNotification> didReceiveLocalNotificationSubject = BehaviorSubject<ReceivedNotification>();
var flutterLocalNotificationsPlugin = NotificationService().flutterLocalNotificationsPlugin;

class ReceivedNotification {
  final int id;
  final String title;
  final String body;
  final String payload;

  ReceivedNotification({
    @required this.id,
    @required this.title,
    @required this.body,
    @required this.payload,
  });
}

class HandleFirebase extends StatefulWidget {
  @override
  _HandleFirebaseState createState() => _HandleFirebaseState();
}

class _HandleFirebaseState extends State<HandleFirebase> {
  static FirebaseAnalytics analytics = FirebaseAnalytics();
  static FirebaseAnalyticsObserver observer = FirebaseAnalyticsObserver(analytics: analytics);
  final FirebaseMessaging firebaseMessaging = FirebaseMessaging();

  var action;
  var title;
  var body;
  final time = DateTime.now();

  void fcmSubscribe() {
    firebaseMessaging.subscribeToTopic(StaticConstant.topicFirebase);
    if (Platform.isIOS) {
      firebaseMessaging.subscribeToTopic(StaticConstant.topicForceIos);
    } else if (Platform.isAndroid) {
      firebaseMessaging.subscribeToTopic(StaticConstant.topicForceAndroid);
    }
  }

  void fcmUnSubscribe() {
    firebaseMessaging.unsubscribeFromTopic(StaticConstant.topicFirebase);
    if (Platform.isIOS) {
      firebaseMessaging.unsubscribeFromTopic(StaticConstant.topicForceIos);
    } else if (Platform.isAndroid) {
      firebaseMessaging.unsubscribeFromTopic(StaticConstant.topicForceAndroid);
    }
  }

  void _configureDidReceiveLocalNotificationSubject() {
    didReceiveLocalNotificationSubject.stream.listen((ReceivedNotification receivedNotification) async {
      print("NOTIF iOS => ${receivedNotification.payload}");
    });
  }

  void _configureSelectNotificationSubject() {
    selectNotificationSubject.stream.listen((String payload) async {

    });
  }

  // ignore: missing_return
  Future<dynamic> onSelectNotification(String payload) {

  }

  showNotification(String action, String title, String message) async {
    var vibrationPattern = Int64List(8);
    vibrationPattern[0] = 0;
    vibrationPattern[1] = 1000;
    vibrationPattern[2] = 2000;
    vibrationPattern[3] = 2000;
    vibrationPattern[4] = 2000;
    vibrationPattern[5] = 2000;
    vibrationPattern[6] = 2000;
    vibrationPattern[7] = 2000;
    var android = new AndroidNotificationDetails(
        StaticConstant.channelidFirebase,
        StaticConstant.channelnameFirebase,
        StaticConstant.channeldescriptionFirebase,
        importance: Importance.Max,
        priority: Priority.High,
        icon: 'ic_launcher_round',
        sound: RawResourceAndroidNotificationSound(''),
        vibrationPattern: vibrationPattern,
        enableLights: true,
        color: Colors.white,
        ledColor: const Color.fromARGB(255, 255, 0, 0),
        ledOnMs: 1000,
        ledOffMs: 500);
    var iOS = new IOSNotificationDetails(presentAlert: true, presentBadge: true, presentSound: true);
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(456, title, body, platform,
        payload: action);
  }

  @override
  void dispose() {
    didReceiveLocalNotificationSubject.close();
    selectNotificationSubject.close();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _requestIOSPermissions();
    _configureDidReceiveLocalNotificationSubject();
    _configureSelectNotificationSubject();
    fcmSubscribe();
    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage => ${message}");
      },
      onLaunch: (Map<String, dynamic> message) async {
        debugPrint("onLaunch => ${message}");
      },
      onBackgroundMessage: onBackgroundMessage,
      onResume: (Map<String, dynamic> message) async {
        debugPrint("onResume => ${message}");
      },
    );
    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true, provisional: true));
    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print("Push Messaging token: $token");
    });
    firebaseMessaging.onTokenRefresh.listen((event) {
      print("Refresh Token: $event");
    });
  }

  static Future<dynamic> onBackgroundMessage(Map<String, dynamic> message) {
    debugPrint('onBackgroundMessage: $message');
    return null;
  }

  void _requestIOSPermissions() {
    flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
        ?.requestPermissions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarBrightness: Brightness.dark));
    return new MaterialApp(
      navigatorObservers: <NavigatorObserver>[observer],
      debugShowCheckedModeBanner: false,
      title: StaticConstant.titleApp,
      theme: new ThemeData(
          primaryColor: Color(0xFF27AE60), accentColor: Colors.greenAccent),
      home: new SplashScreen(),
      routes: <String, WidgetBuilder>{

      },
    );
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  var initializationSettingsAndroid = AndroidInitializationSettings('@drawable/ic_launcher_round');
  var initializationSettingsIOS = IOSInitializationSettings(
      requestAlertPermission: false,
      requestBadgePermission: false,
      requestSoundPermission: false,
      onDidReceiveLocalNotification: (int id, String title, String body, String payload) async {
        didReceiveLocalNotificationSubject.add(ReceivedNotification(id: id, title: title, body: body, payload: payload));
      });
  var initializationSettings = InitializationSettings(
      initializationSettingsAndroid, initializationSettingsIOS);
  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification:(String payload) async {
        if (payload != null) {
          debugPrint('notification payload: ' + payload);
        }
        selectNotificationSubject.add(payload);
      });

  runZoned<Future<Null>>(() async {
    runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HandleFirebase(),
    ));
  }, onError: (error, stackTrace) async {
    await FlutterCrashlytics()
        .reportCrash(error, stackTrace, forceCrash: false);
  });
}

Please ignore other plugin that i use

Expected behavior
I want to show all background notification, onResume & onLaunch, like android work perfectly

Additional context
I use postman to send notification. heres notif that i send

{
    "notification": {
        "body": "This is Body", 
        "title": "This is Title"
    }, 
    "data": {
        "action": "Goto Here", 
        "data": {
            "updated_at":"2019-09-01 18:34:49"
        }, 
        "action_click": "FLUTTER_NOTIFICATION_CLICK"
    },
	"to": "<TOKEN>"
}

and heres onMessage log that i received

{
	from: 4242036, 
	action: Goto Here, 
	data: {
	      "updated_at":"2019-09-01 18:34:49"
	}, 
	action_click: FLUTTER_NOTIFICATION_CLICK, 
	notification: {
	      title: This is Title, 
	      e: 1, 
	      body: This is Body
	},
	 collapse_key: "<packageName>"
}

Flutter doctor
Jepretan Layar 2020-05-27 pukul 23 16 34

@TahaTesser
Copy link

duplicate of #2284

@firebase firebase locked and limited conversation to collaborators Jul 30, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants