🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / FLUTTER / android ve ios fcm push firebase cloud messaging fast entegre kullanımı 2023

1-) FLUTTER - android ve ios fcm push firebase cloud messaging fast entegre kullanımı

 

 

***************** ANDROİD ENTEGRESİ *****************

github kaynak : https://github.com/ramazanhaber/flutterandroidfcmpush

 

 

1.ADIM -  android->app->src->main->AndroidManifest.xml'e INTERNET ve CleartextTraffic i ekle . aşağıdaki gibi

 

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    
package="com.ramzey.fcmandroidios"

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

   <
application
       
android:usesCleartextTraffic="true"

 

 

 

2.ADIM - android->app->build.gradle'a (minSdkVersion 21)(targetSdkVersion 33)(compileSdkVersion 33) yap

 

3.ADIM - https://console.firebase.google.com/u/0/ adresinden create a project diyip rastegele isim ver ve bir hesabın oluşuacak

4.ADIM - aşağıdaki gibi android yazan kısımdan ilerle

 

5.ADIM -

6.ADIM - android->app->build.gradleye (apply plugin: 'com.google.gms.google-services') ve en aşağıya bunu ekle

 

implementation platform('com.google.firebase:firebase-bom:31.2.3')
implementation
'com.google.firebase:firebase-analytics-ktx'

 

7.ADIM - android->build.gradleye (classpath 'com.google.gms:google-services:4.3.15') bunu ekle

8.ADIM - uygulamayı kapat aç

9.ADIM - firebase->proje settings->cloud messaging-> Enable yap -> orası okey dicek ve server key vericek aşağıdaki gibi

 

 

10.ADIM -Aşağıdakileri terminale yaz ve çalıştır

flutter pub add firebase_core

flutter pub add firebase_messaging

flutter pub add push_fire_notifications

11.ADIM - main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:push_fire_notifications/pushnotification.dart';

Future<void> main() async {
  
WidgetsFlutterBinding.ensureInitialized();
  
try{
    
await Firebase.initializeApp();
  }
catch(ex){
  }
  runApp(
MyApp());
}

class MyApp extends StatelessWidget {
   
MyApp({super.key});

  
@override
  
Widget build(BuildContext context) {
    
return 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("2 "+payload);
      },
      onTapAppTerminatedNotification: (
String payload) {
        
// This function use for on tap notification when
        // app is terminated mode
        
print("3 "+payload);
      },
      child:
MaterialApp(
        title:
'Flutter Demo',
        debugShowCheckedModeBanner:
false,
        theme:
ThemeData(

          primarySwatch:
Colors.blue,
        ),
        home:
Scaffold(appBar: AppBar(title: Text("FCM :) "),),body: Container(child: Text("Hello"),),),
      ),
    );
  }
}

 

12.ADIM - örnek telefona bildirim göndermek için postman deki alanlar aşağıdaki gibi olucak

 

post edilecek url : https://fcm.googleapis.com/fcm/send

HEADERE EKLENECEK PARAM :

key = Authorization

Value = key=AAAAW4rLnrk:APA91bGEYeev_aYl_RO4SZUrmkd-uxbJaa-biT18xOmyl9MsZp8rdHdvy13F1qzH1gG3xiObAzcvWQ1MuVIIC7r3bV-M1dN9PywmkVUcnjx5

BODY -> ROW -> JSON  :

{

   "to""dgjbLgSsR8uDhLDnQuDblV:APA91bFCfsmT7zhi7qxwf9RDJG9tVCu_doKdRNvqOs0-4_ax7CmJy_9MQ1Jqj4nL3cmDCBt3tzGv8zFVng_G_lYRFnSP_mJekwo8K-jz100tmrXfvC0hUeQJOYB_2Ux7hKM9Oh5jC3Hf",

   "notification": {

    "body""akakçede indirim hemen girin %40 indirim",

    "title""Selamün aleyküm 23",

    "content_available" : true,

    "priority" : "high"

   }

}

 

EKRAN GÖRÜNTÜSÜ

 

 

***************** İOS ENTEGRESİ **********************

 

NOT ANDROİDDEDE ÇALIŞIR android ios github kaynak : https://github.com/ramazanhaber/iosfcm11

 

 

0-AŞAĞIDAKİLERİ KUR

 

flutter pub add firebase_core

flutter pub add firebase_messaging

flutter pub add flutter_local_notifications  açıklama flutter_local_notifications: ^9.9.1

 

 

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

 

 

 

 <key>FirebaseAppDelegateProxyEnabled</key>

 <false/>

 

0.ADIM  xcode ekle

 

1.ADIM 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.ADIM 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

 

 

 

 

 

 

3.ADIM İ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.

 

 

4.ADIM (ios->Runner->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)
   }
}

 

 

 

 

 

5.ADIM (LocalNotificationService.dart)

 

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


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

  
static get onDidReceiveLocalNotification => null;

  
static void initialize() {
    
try{
      
// initializationSettings  for Android


      
const AndroidInitializationSettings androidInitializationSettings =
      
AndroidInitializationSettings("@mipmap/ic_launcher");

      
IOSInitializationSettings iosInitializationSettings =
      
IOSInitializationSettings(
        requestAlertPermission:
true,
        requestBadgePermission:
true,
        requestSoundPermission:
true,
        onDidReceiveLocalNotification:
onDidReceiveLocalNotification,
      );

      
final InitializationSettings settings = InitializationSettings(
        android:
androidInitializationSettings,
        iOS:
iosInitializationSettings,
      );

       
_notificationsPlugin.initialize(
        
settings,
         onSelectNotification: (
String? id) async {
      },
      );


    }
catch(ex){
      print(
"hst "+ex.toString());
    }
  }

  
static void createanddisplaynotification(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(
          
"egitimbildirim",
          
"egitimbildirimchannel",
          importance:
Importance.max,
          priority:
Priority.high,
        ),
      );

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

 

 

6.ADIM (main.dart)

 

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutterandroidfcmpush/homepage.dart';

import 'LocalNotificationService.dart';

@pragma('vm:entry-point')
Future<void> backgroundHandler(RemoteMessage message) async {
  
// print(message.data.toString());
  // print(message.notification!.title);
}

Future<void> main() async {

  
WidgetsFlutterBinding.ensureInitialized();

  
try{
    
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 ?? ""));
    }

  }
catch(ex){
  }

  runApp(
MyApp());
}

class MyApp extends StatelessWidget {
   
MyApp({super.key});
  
// rambo
  // This widget is the root of your application.
  
@override
  
Widget build(BuildContext context) {
    
return  MaterialApp(
      title:
'Flutter Demo',
      debugShowCheckedModeBanner:
false,
      theme:
ThemeData(

        primarySwatch:
Colors.blue,
      ),
      home:  
HomePage(),
    );
  }}

 

7.ADIM(sabitler.dart)

 

class Sabitler {
  
static String token="";
}

 

 

8.ADIM (homepage.dart)

 

 

import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterandroidfcmpush/sabitler.dart';

import 'LocalNotificationService.dart';

class HomePage extends StatefulWidget {
  
const HomePage({Key? key}) : super(key: key);

  
@override
  
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
   
@override
  
void initState() {
    
// TODO: implement initState
    
super.initState();
    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');

      Sabitler.token = value!;

 

      Clipboard.setData(ClipboardData(text: Sabitler.token));

 

      setState(() {});

    });

  }


  
@override
  
Widget build(BuildContext context) {
    
return Scaffold(
        appBar:
AppBar(
          title:
Text("FCM İOS İÇİN"),
        ),
        body:
Container(
          child:
Text(Sabitler.token),
        ));
  }
}

 

 

 

9.ADIM

 

10.ADIM

 

 

 

 

 

firebase hatası giderme cocoapods vs

https://stackoverflow.com/questions/69073542/firebase-crashlytics-was-resolved-to-2-2-1-which-depends-on-firebase-crashlytic

 

 

***************** DİĞER BAKMASANDA OLUR  *****************

 

 

kaynak : https://www.youtube.com/watch?v=VeygRpCWHbA&ab_channel=CodePie

 

 

 

DİĞER

 

https://pub.dev/packages/push_fire_notifications

 

Info.plist aşağıdakini ekle

 

 <keyFirebaseAppDelegateProxyEnabled</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ü :

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)

   }

}

 

 

 2023 Nisan 11 Salı
 541