🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / FLUTTER / Flutter Ios and Android Send Push Notification fcm 2022 bildirim gönderme kullanımı

1-) FLUTTER - Flutter Ios and Android Send Push Notification fcm 2022 bildirim gönderme kullanımı

 

BİLDİRİM İÇİN İOS TELEFON KULLAN. EMÜLATORDA ÇALIŞMAZ . AYRICA ŞU KOMUT İLE ÇALIŞTIR. YOKSA UYGULAMAYI KAPATINCA TEKRAR AÇILMAZ.

 

UYARI pod install için İLK ÖNCE Runner.xcodeproj YAP SONRA Runner.xcworkspace İLE ACHİVE YAP

 

-> Flutter run --release

 

 

örn uygulama linki : https://drive.google.com/file/d/1Vu6TqDnEeexMAVr4b0gEe3PNjF7NOTX4/view?usp=sharing

 

 

     ***************** İOS KURULUM VE KULLANIMI*****************

 

 

0- Info.plist e aşağıdakini ekle

 

 <key>FirebaseAppDelegateProxyEnabled</key>

<false/>

 

0- pubspec.yaml aşağıdakileri ekle

 

# fcm android ios bildirim
firebase_core: ^1.20.0
firebase_messaging: ^12.0.1
flutter_local_notifications: ^9.7.0

 

0-)  xcode ekle

 

1- ilk olarak GoogleService-Info.plist dosyasını XCODE idesinde Runner klasörüne sağ tıklayıp "Add files to Runner" diyelim

 

                    

 

 

 

 

 

NOT BURASI ÇOK ÖNEMLİ ADD FİLES TO RUNNER DEDİKTEN SONRA GoogleService-Info.plist DOSYASINI SEÇMELİSİN

 

2- AppDelegate.swift

 

 

import UIKit
import Flutter
import Firebase
import FirebaseMessaging

@UIApplicationMain
@objc class
AppDelegate: FlutterAppDelegate {

  override func application(
    _ application:
UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
  FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with:
self)
    
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
   
override func application(_ application: UIApplication,
    
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

     Messaging.messaging().
apnsToken = deviceToken
     print(
"Token2: \(deviceToken)")
     
super.application(application,
     didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
   }
}

 



3- main.dart

 

 

 

import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:rmosflutterguest/langs/LocaleKeys.dart';
import 'package:rmosflutterguest/page/ekhizmetler/sitatik_sinif.dart';
import 'package:rmosflutterguest/page/login/login_page2.dart';

import 'fcmgoogle/local_notification_service.dart';
import 'langs/AppConstant.dart';
import 'page/ekhizmetler/httpsertifika.dart';
import 'page/login/login_page1.dart';

Future<void> backgroundHandler(RemoteMessage message) async {
  
// print(message.data.toString());
  // print(message.notification!.title);
}

Future<void> main() async {
  
WidgetsFlutterBinding.ensureInitialized();

  
try{
    
//fcm
    
await Firebase.initializeApp();
    
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
    
LocalNotificationService.initialize();
    
//(sonradan eklendi) Update the iOS foreground notification presentation options to allow heads up notifications.
    
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert:
true,
      badge:
true,
      sound:
true,

    );

    
var _messaging = FirebaseMessaging.instance;
    
NotificationSettings settings = await _messaging.requestPermission(
        alert:
true, badge: true, sound: true, provisional: false);

    
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      
String? token = await _messaging.getToken();
      print(
"IOS TOKEN : " + (token ?? ""));
    }

    
await EasyLocalization.ensureInitialized();

    runApp(
      
EasyLocalization(
        supportedLocales:
AppConstant.SUPPORTED_LOCALE,
        path:
AppConstant.LANG_PATH,
        
//fallbackLocale: Locale('tr','TR'),
        
child: MyApp(),
      ),
    );
    configLoading();
  }
catch(ex){
    print(
"hata "+ex.toString());
  }

}

void configLoading() {
  
EasyLoading.instance
    
..displayDuration = const Duration(milliseconds: 1200)
    ..
indicatorType = EasyLoadingIndicatorType.fadingCircle
    
..loadingStyle = EasyLoadingStyle.dark
    
..indicatorSize = 45.0
    
..radius = 10.0
    
..progressColor = Colors.yellow
    
..backgroundColor = Colors.green
    
..indicatorColor = Colors.yellow
    
..textColor = Colors.yellow
    
..maskColor = Colors.blue.withOpacity(0.5)
    ..
userInteractions = true
    
..dismissOnTap = false;
}

class MyApp extends StatefulWidget {
  
const MyApp({Key? key}) : super(key: key);
  
static const String _title = 'RMOS GUEST X';

  
@override
  
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  
@override
  
Widget build(BuildContext context) {
    
return MaterialApp(
      debugShowCheckedModeBanner:
false,
      localizationsDelegates: context.
localizationDelegates,
      supportedLocales: context.
supportedLocales,
      title:
MyApp._title,
      locale: context.
locale,
      home:
LoginPage1(),
      builder:
EasyLoading.init(),
      localeResolutionCallback:
LocaleKeys.varsayilanTelefonunDili,
    );
  }

  
@override
  
void initState() {
    
// TODO: implement initState
    
super.initState();
    
HttpOverrides.global = MyHttpOverrides();

    fcmRun();
  }

  
void fcmRun() {


 
/*
    // uygulama kapalı iken çalışacak metot
    FirebaseMessaging.instance.getInitialMessage().then(
      (message) {
        print("1-> FirebaseMessaging.instance.getInitialMessage()");
      },
    );*/

 


    
// 2. This method only call when App in forground it mean app must be opened
// uygulama açıkken tıklanınca çalışan metot
FirebaseMessaging.onMessage.listen(
  (message) {
    print(
"2-> FirebaseMessaging.instance.getInitialMessage()");
    
if(Platform.isAndroid){
      
LocalNotificationService.createanddisplaynotification(message);
    }
  },
);


    
// 3. This method only call when App in background and not terminated(not closed)
    // uygulama açık ama arka plandayken çalışan metot
    
FirebaseMessaging.onMessageOpenedApp.listen(
      (message) {
print(
"3-> FirebaseMessaging.onMessageOpenedApp.listen");

      },
    );

    
FirebaseMessaging.instance
        
.subscribeToTopic("all")
        .then((value) => print(
"topic all olarak eklendi"));

    
FirebaseMessaging.instance.getToken().then((value) {
      print(
'firebaseToken $value');
      
StatikSinif.token = value;
    });

  }
}

 

 

4- LocalNotificationService.dart

 

 

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';


class LocalNotificationService {
  
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
  FlutterLocalNotifications
Plugin();

  
static void initialize() {
    
try{
      
// initializationSettings  for Android
      
const InitializationSettings initializationSettings =
      Initializa
tionSettings(
        
android: AndroidInitializationSettings("@mipmap/ic_launcher"),
      
);

      _not
ificationsPlugin.initialize(
        initi
alizationSettings,
        onSel
ectNotification: (String? id) async {
        },
      );
    }
catch(ex){
      
print("hst "+ex.toString());
    
}
  }

  static void cr
eateanddisplaynotification(RemoteMessage message) async {
    
try {
      
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;

      
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
        alert:
true,
        badge:
true,
        
sound: true,
      
);

      
var _messaging = FirebaseMessaging.instance;
      
NotificationSettings settings = await _messaging.requestPermission(
          alert:
true, badge: true, sound: true, provisional: false);

      const
NotificationDetails notificationDetails = NotificationDetails(
        
android: AndroidNotificationDetails(
          
"guestbildirim",
          
"guestbildirimchannel",
          impo
rtance: Importance.max,
          priority: Pri
ority.high,
        
),
      );

      
await _notificationsPlugin.show(
        id,
        m
essage.notification!.title!+" aa",
        mes
sage.notification!.body,
        notificationDetails,
        
//payload: message.data['_id'],
      
);
    }
on Exception catch (e) {
      print(e);
    }
  }
}

 

 

 

 

4.1- Android->app->build.gradle (ÖNEMLİ)

 

   


apply
plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    
compileSdkVersion 32
    
compileOptions {
        
sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    
}
    
kotlinOptions {
        
jvmTarget = '1.8'
    
}

    
sourceSets {
        
main.java.srcDirs += 'src/main/kotlin'
    
}

    
defaultConfig {
      
 applicationId "com.rmos.rmosflutterguest"
        
minSdkVersion 21 // normalde 16 idi. ama otekaktivite html goruntulemek için 19 yaptım, FCM için 21 yaptım
        
targetSdkVersion 32
        
versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    
}
}

dependencies {
    
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    
implementation platform('com.google.firebase:firebase-bom:30.2.0')
    implementation
'com.google.firebase:firebase-analytics'
}

 

4.2- Android->build.gradle (ÖNEMLİ)

 

   



buildscript {
    
ext.kotlin_version = '1.6.10'
    
repositories {
        
google()
        mavenCentral()
    
}

    
dependencies {
        
classpath 'com.android.tools.build:gradle:7.2.0'
        
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        
classpath 'com.google.gms:google-services:4.3.13'
    
}
}

allprojects {
    
repositories {
        
google()
        mavenCentral()
    
}
}

rootProject.buildDir = '../build'
subprojects {
    
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    
project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    
delete rootProject.buildDir
}

 

 

 

 

 

 

5- ios Devoloper account daki keyid ve teamid -> FCM deki ile aynı olacak -> aşağıdaki iki resimden görebilirsiniz

 

https://developer.apple.com/account/resources/certificates/list

 

 

 

 

 

 

 

 

6- İos Devoloper Keys bir tane olsa yeter tüm projede onu kullanabiliriz -> FCM ye .p8 uzantılı downloand ettiğimiz dosya ile birlikte key ve team id ile kullanabiliriz. bu dosyayı kaybetmeyin.

 

 

 

 

7- İos  -> Identifiers -> ekle dedikten sonra -> App IDs seçilir -> aşağıdaki gibi

 

 

 

ARDINDAN

 

 

ARDINDAN

 

ARDINDAN

ARDINDAN

 

 

8- BİLDİRİM İÇİN İOS TELEFON KULLAN. EMÜLATORDA ÇALIŞMAZ . AYRICA ŞU KOMUT İLE ÇALIŞTIR. YOKSA UYGULAMAYI KAPATINCA TEKRAR AÇILMAZ.

 

-> Flutter run --release

 

 

***************** ANDROİD KURULUM VE KULLANIMI*****************

 

EKRAN GÖRÜNTÜSÜ

 

 

 

1-) Bildirim göndermek için bu adresten firebase cloud messaging json dosyamızı oluştururuz https://console.firebase.google.com/

 

 

2-) ARDINDAN

 

 

3-) ARDINDAN

 

 

4-) FCM JSON dosyasını buraya atarız

 

 

5-) AndroidManifest.xml

 

<uses-permission android:name="android.permission.INTERNET"/>

<
application
    
android:name="${applicationName}"
    
android:label="Marmara Enstitü"
    
android:usesCleartextTraffic="true"

...

..

..

<activity

<meta-data
    
android:name="com.google.firebase.messaging.default_notification_channel_id"
    
android:value="marmarabildirim"/>

 

 

6-) FCM CONSOLEDEN AŞAĞIDAKİ SERVER TOKENİ AL

 

 

7-) POSTMAN DE BURAYA YAZ

 

KEY --> Authorization

VALUE --> key=AAAA0gZhxfg:RAMAAPA91bHc4FJPJK5A0pZ_FJ3m_zxzT5todU2LUwilIhlY2CsX9jjA0r8ZxbXq6en4iSsIWLvuy-DhyUMpKg-Q2_myFw6HHiMtI_0u7IgW2wdSBGu2QakjSE6GmsjVBaNqYZAN

 

8-) POSTMAN DE TÜM CİHAZLARA GÖNDERMEK İÇİN FLUTTER A YAZDIĞIN "all" ı böyle gönderebilirsin

 

https://fcm.googleapis.com/fcm/send

{

   "to""/topics/all",

   "notification": {

    "body""Hello2",

    "title""This is test message.2",

    "image""https://i.ibb.co/HxsdSdP/logo.jpg",

    "content_available" : true,

    "priority" : "high"

   }

}

 

 

FirebaseMessaging.instance
    
.subscribeToTopic("all")
    .then((value) => print(
"topic all olarak eklendi"));

FirebaseMessaging.instance.getToken().then((value) {
  print(
'firebaseToken $value');
});

 

9-) AŞAĞIDAKİ O BİLDİRİMİ KULLAN DEMEK

 

 

marmarabildirim

 

 

10-) ANDROİD FCM OLUŞTURURKEN google-services.json u buraya at

 

 

 

 

Android ve ios bildirim json örneği

 

 

POST LİNK -> https://fcm.googleapis.com/fcm/send

 

{

    "to""dC1BSBfJMy6eSa0e7n-",

    "priority"10,

    "notification": {

        "body""selam2",

        "title""hey2"

    }

}

 


HERKESE GÖNDERMEK İSTERSEN
{

   "to""/topics/all",

   "notification": {

    "body""Zeynep",

    "title""Selamün aleyküm2345",

    "image""https://i.ibb.co/HxsdSdP/logo.jpg",

    "content_available" : true,

    "priority" : "high"

   }

}

 

 

POST LİNK -> https://fcm.googleapis.com/fcm/send

 

 

Authorization

 

key=ServerKeyAAAAlG



kaynak : https://www.youtube.com/watch?v=TXod1rLVF7M&ab_channel=InventorCode

ayıca kaynak : https://github.com/JohannesMilke/send_push_notifications/

kaynak3 ios : https://firebase.flutter.dev/docs/messaging/apple-integration/

 

 

 

18- yeni paket android,ios denendi çalışıyor : https://pub.dev/packages/push_fire_notifications

 

Info.plist aşağıdakini ekle

 

 <key>FirebaseAppDelegateProxyEnabled</key>

 <false/>

 

flutter pub add push_fire_notifications

 

1- main.dart

 

child: PushFireNotifications(
  fcmTokenGet: (
String token) {
    
// Here we can get FCM token when app starts.
    
print("TOKEN : "+token);
  },
  onNotification: (
String payload) {

    
// This function trigger whenever notification occurs
    // get data in payload
    
print("1 "+payload);
  },
  onTapNotification: (
String payload) {

    
// This function use for on tap notification when app
    // is running mode
    
print("1 "+payload);
  },
  onTapAppTerminatedNotification: (
String payload) {
    
// This function use for on tap notification when
    // app is terminated mode
    
print("1 "+payload);
  },
  child:
MaterialApp(

 

 

 

yeni paketteki şu hata çözümü :  @pragma('vm:entry-point')

E/flutter ( 3444): [ERROR:flutter/shell/common/shell.cc(93)] Dart Error: Dart_LookupLibrary: library 'package:push_fire_notifications/push_notification/firebase_notification_api.dart' not found.

 

 

 

yeni pakettede bunu yap yoksa tokeni ios tarafında yeniler ve haberin olmaz. Birde add files to runner yap

 

 

import UIKit

import Flutter

import Firebase

import FirebaseMessaging

 

@UIApplicationMain

@objc class AppDelegate: FlutterAppDelegate {

 

  override func application(

    _ application: UIApplication,

    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?

  ) -> Bool {

  FirebaseApp.configure()

    GeneratedPluginRegistrant.register(with: self)

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)

  }

 

   override func application(_ application: UIApplication,

    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

 

     Messaging.messaging().apnsToken = deviceToken

     print("Token2: \(deviceToken)")

     super.application(application,

     didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)

   }

}

 

 

 

 

DİĞER PAKETLERİ İNCELEYEBİLRSİN
https://pub.dev/packages/flutter_fcm

web için : https://pub.dev/packages/firebase_cloud_messaging_interop

 

 2023 Nisan 11 Salı
 638