รับข้อความในแอป Flutter

ระบบจะจัดการข้อความขาเข้าแตกต่างกันไปตามสถานะของอุปกรณ์ หากต้องการทำความเข้าใจสถานการณ์เหล่านี้และวิธีผสานรวม FCM เข้ากับแอปพลิเคชันของคุณเอง คุณต้องกำหนดสถานะต่างๆ ที่อุปกรณ์อาจมีก่อน

รัฐ คำอธิบาย
เบื้องหน้า เมื่อแอปพลิเคชันเปิดอยู่ แสดงอยู่ และใช้งานอยู่
ความเป็นมา เมื่อแอปพลิเคชันเปิดอยู่ แต่ทำงานในเบื้องหลัง (ย่อขนาด) โดยปกติแล้วเหตุการณ์นี้จะเกิดขึ้นเมื่อผู้ใช้กดปุ่ม "หน้าแรก" ในอุปกรณ์ เปลี่ยนไปใช้แอปอื่นโดยใช้ตัวสลับแอป หรือเปิดแอปพลิเคชันในแท็บอื่น (เว็บ)
สิ้นสุด เมื่ออุปกรณ์ล็อกอยู่หรือแอปพลิเคชันไม่ได้ทำงาน

มีข้อกำหนดเบื้องต้น 2-3 ข้อที่ต้องเป็นไปตามก่อนที่แอปพลิเคชันจะรับเพย์โหลดข้อความผ่าน FCM ได้

  • แอปพลิเคชันต้องเปิดอย่างน้อย 1 ครั้ง (เพื่อให้ลงทะเบียนกับ FCM ได้)
  • ใน iOS หากผู้ใช้ปัดแอปพลิเคชันออกจากตัวสลับแอป จะต้องเปิดแอปพลิเคชันอีกครั้งด้วยตนเองเพื่อให้ข้อความในเบื้องหลังเริ่มทำงานอีกครั้ง
  • ใน Android หากผู้ใช้บังคับปิดแอปจากการตั้งค่าอุปกรณ์ จะต้องเปิดแอปอีกครั้งด้วยตนเองเพื่อให้ข้อความเริ่มทำงาน
  • ในเว็บ คุณต้องขอโทเค็น (โดยใช้ getToken()) พร้อมใบรับรองการแจ้งเตือนแบบพุชบนเว็บ

ขอสิทธิ์รับข้อความ

ใน iOS, macOS, เว็บ และ Android 13 (หรือใหม่กว่า) คุณต้องขอสิทธิ์จากผู้ใช้ก่อนจึงจะรับเพย์โหลด FCM ในอุปกรณ์ได้

firebase_messaging แพ็กเกจมี API ที่เรียบง่ายสำหรับการขอสิทธิ์ผ่านเมธอด requestPermission API นี้ยอมรับอาร์กิวเมนต์ที่มีชื่อหลายรายการซึ่งกำหนดประเภทสิทธิ์ที่คุณต้องการขอ เช่น ไม่ว่าการรับส่งข้อความที่มีเพย์โหลดการแจ้งเตือนจะทริกเกอร์เสียงหรืออ่านข้อความผ่าน Siri ได้หรือไม่ โดยค่าเริ่มต้น เมธอดจะขอสิทธิ์เริ่มต้นที่เหมาะสม Reference API มีเอกสารประกอบทั้งหมดเกี่ยวกับวัตถุประสงค์ของสิทธิ์แต่ละรายการ

หากต้องการเริ่มต้นใช้งาน ให้เรียกใช้เมธอดจากแอปพลิเคชัน (ใน iOS ระบบจะแสดงโมดัลเนทีฟ ส่วนในเว็บ ระบบจะทริกเกอร์โฟลว์ API เนทีฟของเบราว์เซอร์)

FirebaseMessaging messaging = FirebaseMessaging.instance;

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

print('User granted permission: ${settings.authorizationStatus}');

คุณใช้authorizationStatusพร็อพเพอร์ตี้ของออบเจ็กต์ NotificationSettings ที่ส่งคืนจากคำขอเพื่อพิจารณาการตัดสินใจโดยรวมของผู้ใช้ได้

  • authorized: ผู้ใช้ได้รับสิทธิ์
  • denied: ผู้ใช้ปฏิเสธการให้สิทธิ์
  • notDetermined: ผู้ใช้ยังไม่ได้เลือกว่าจะให้สิทธิ์หรือไม่
  • provisional: ผู้ใช้ได้รับสิทธิ์ชั่วคราว

พร็อพเพอร์ตี้อื่นๆ ใน NotificationSettings จะแสดงว่ามีการเปิดใช้ ปิดใช้ หรือไม่รองรับสิทธิ์ที่เฉพาะเจาะจงในอุปกรณ์ปัจจุบันหรือไม่

เมื่อได้รับสิทธิ์และเข้าใจสถานะของอุปกรณ์ประเภทต่างๆ แล้ว ตอนนี้แอปพลิเคชันของคุณก็เริ่มจัดการเพย์โหลด FCM ที่เข้ามาได้แล้ว

การจัดการข้อความ

เพย์โหลดขาเข้าของประเภทข้อความต่างๆ ต้องมีการติดตั้งใช้งานที่แตกต่างกันเพื่อจัดการเพย์โหลดเหล่านั้น โดยขึ้นอยู่กับสถานะปัจจุบันของแอปพลิเคชัน

ข้อความที่ทำงานอยู่เบื้องหน้า

หากต้องการจัดการข้อความขณะที่แอปพลิเคชันทำงานอยู่เบื้องหน้า ให้ฟังสตรีม onMessage

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Got a message whilst in the foreground!');
  print('Message data: ${message.data}');

  if (message.notification != null) {
    print('Message also contained a notification: ${message.notification}');
  }
});

สตรีมมี RemoteMessage ซึ่งให้รายละเอียด ข้อมูลต่างๆ เกี่ยวกับเพย์โหลด เช่น แหล่งที่มา รหัสที่ไม่ซ้ำ เวลาที่ส่ง มีการแจ้งเตือนหรือไม่ และอื่นๆ เนื่องจากระบบดึงข้อความขณะที่แอปพลิเคชันทำงานอยู่เบื้องหน้า คุณจึงเข้าถึงสถานะและบริบทของแอปพลิเคชัน Flutter ได้โดยตรง

ข้อความที่ทำงานอยู่เบื้องหน้าและการแจ้งเตือน

ข้อความการแจ้งเตือนที่เข้ามาขณะที่แอปพลิเคชันทำงานอยู่เบื้องหน้าจะไม่แสดงการแจ้งเตือนที่มองเห็นได้โดยค่าเริ่มต้น ทั้งใน Android และ iOS อย่างไรก็ตาม คุณสามารถลบล้างลักษณะการทำงานนี้ได้โดยทำดังนี้

  • ใน Android คุณต้องสร้างแชแนลการแจ้งเตือน "ลำดับความสำคัญสูง"
  • ใน iOS คุณสามารถอัปเดตตัวเลือกการนำเสนอสำหรับแอปพลิเคชันได้

ข้อความในเบื้องหลัง

กระบวนการจัดการข้อความในเบื้องหลังจะแตกต่างกันในแพลตฟอร์มเนทีฟ (Android และ Apple) และแพลตฟอร์มบนเว็บ

แพลตฟอร์ม Apple และ Android

จัดการข้อความในเบื้องหลังโดยการลงทะเบียนแฮนเดิลonBackgroundMessage เมื่อได้รับข้อความ ระบบจะสร้างไอโซเลตรุ่นใหม่ (Android เท่านั้น, iOS/macOS ไม่ต้องใช้ไอโซเลตแยกต่างหาก) ซึ่งช่วยให้คุณจัดการข้อความได้แม้ในขณะที่แอปพลิเคชันไม่ได้ทำงาน

สิ่งที่ควรทราบเกี่ยวกับตัวแฮนเดิลข้อความในเบื้องหลังมีดังนี้

  1. โดยต้องไม่ใช่ฟังก์ชันที่ไม่ระบุชื่อ
  2. ต้องเป็นฟังก์ชันระดับบนสุด (เช่น ไม่ใช่วิธีการของคลาสที่ต้องมีการเริ่มต้น)
  3. เมื่อใช้ Flutter เวอร์ชัน 3.3.0 ขึ้นไป คุณต้องใส่คำอธิบายประกอบให้กับตัวแฮนเดิลข้อความด้วย @pragma('vm:entry-point') เหนือการประกาศฟังก์ชัน (มิฉะนั้นระบบอาจนำออกระหว่างการเพิ่มประสิทธิภาพโค้ดสำหรับโหมดรีลีส)
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();

  print("Handling a background message: ${message.messageId}");
}

void main() {
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

เนื่องจากตัวแฮนเดิลทำงานในไอโซเลตของตัวเองนอกบริบทของแอปพลิเคชัน คุณจึงอัปเดตสถานะของแอปพลิเคชันหรือเรียกใช้ตรรกะที่ส่งผลต่อ UI ไม่ได้ อย่างไรก็ตาม คุณสามารถดำเนินการเชิงตรรกะ เช่น คำขอ HTTP, ดำเนินการ IO (เช่น อัปเดตพื้นที่เก็บข้อมูลในเครื่อง), สื่อสารกับปลั๊กอินอื่นๆ เป็นต้น

นอกจากนี้ เราขอแนะนำให้คุณเขียนตรรกะให้เสร็จสมบูรณ์โดยเร็วที่สุด การเรียกใช้งานที่ใช้เวลานานและต้องใช้ทรัพยากรมากจะส่งผลต่อประสิทธิภาพของอุปกรณ์ และอาจทำให้ระบบปฏิบัติการสิ้นสุดกระบวนการ หากงานทำงานนานกว่า 30 วินาที อุปกรณ์อาจหยุดกระบวนการโดยอัตโนมัติ

เว็บ

บนเว็บ ให้เขียน Service Worker ของ JavaScript ซึ่งทำงานในเบื้องหลัง ใช้ Service Worker เพื่อจัดการข้อความในเบื้องหลัง

หากต้องการเริ่มต้นใช้งาน ให้สร้างไฟล์ใหม่ในไดเรกทอรี web แล้วตั้งชื่อว่า firebase-messaging-sw.js

// Please see this file for the latest firebase-js-sdk version:
// https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core_web/lib/src/firebase_sdk_version.dart
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js");

firebase.initializeApp({
  apiKey: "...",
  authDomain: "...",
  databaseURL: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "...",
});

const messaging = firebase.messaging();

// Optional:
messaging.onBackgroundMessage((message) => {
  console.log("onBackgroundMessage", message);
});

ไฟล์ต้องนำเข้าทั้ง SDK ของแอปและ SDK ของการรับส่งข้อความ เริ่มต้น Firebase และแสดงตัวแปร messaging

จากนั้นต้องลงทะเบียนผู้ปฏิบัติงาน ในindex.html ให้ลงทะเบียน Worker โดยแก้ไขแท็ก <script> ที่เริ่มต้น Flutter ดังนี้

<script src="flutter_bootstrap.js" async>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register('firebase-messaging-sw.js', {
        scope: '/firebase-cloud-messaging-push-scope',
      });
    });
  }
</script>

หากยังใช้ระบบการสร้างเทมเพลตแบบเดิมอยู่ คุณสามารถลงทะเบียน Worker ได้โดยแก้ไขแท็ก <script> ที่เริ่มต้น Flutter ดังนี้

<html>
<body>
  <script>
      var serviceWorkerVersion = null;
      var scriptLoaded = false;
      function loadMainDartJs() {
        if (scriptLoaded) {
          return;
        }
        scriptLoaded = true;
        var scriptTag = document.createElement('script');
        scriptTag.src = 'main.dart.js';
        scriptTag.type = 'application/javascript';
        document.body.append(scriptTag);
      }

      if ('serviceWorker' in navigator) {
        // Service workers are supported. Use them.
        window.addEventListener('load', function () {
          // Register Firebase Messaging service worker.
          navigator.serviceWorker.register('firebase-messaging-sw.js', {
            scope: '/firebase-cloud-messaging-push-scope',
          });

          // Wait for registration to finish before dropping the <script> tag.
          // Otherwise, the browser will load the script multiple times,
          // potentially different versions.
          var serviceWorkerUrl =
            'flutter_service_worker.js?v=' + serviceWorkerVersion;

          navigator.serviceWorker.register(serviceWorkerUrl).then((reg) => {
            function waitForActivation(serviceWorker) {
              serviceWorker.addEventListener('statechange', () => {
                if (serviceWorker.state == 'activated') {
                  console.log('Installed new service worker.');
                  loadMainDartJs();
                }
              });
            }
            if (!reg.active && (reg.installing || reg.waiting)) {
              // No active web worker and we have installed or are installing
              // one for the first time. Simply wait for it to activate.
              waitForActivation(reg.installing ?? reg.waiting);
            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
              // When the app updates the serviceWorkerVersion changes, so we
              // need to ask the service worker to update.
              console.log('New service worker available.');
              reg.update();
              waitForActivation(reg.installing);
            } else {
              // Existing service worker is still good.
              console.log('Loading app from service worker.');
              loadMainDartJs();
            }
          });

          // If service worker doesn't succeed in a reasonable amount of time,
          // fallback to plaint <script> tag.
          setTimeout(() => {
            if (!scriptLoaded) {
              console.warn(
                'Failed to load app from service worker. Falling back to plain <script> tag.'
              );
              loadMainDartJs();
            }
          }, 4000);
        });
      } else {
        // Service workers not supported. Just drop the <script> tag.
        loadMainDartJs();
      }
  </script>
</body>

จากนั้นรีสตาร์ทแอปพลิเคชัน Flutter ระบบจะลงทะเบียน Worker และจัดการข้อความในเบื้องหลังผ่านไฟล์นี้

การจัดการการโต้ตอบ

เนื่องจากการแจ้งเตือนเป็นคิวที่มองเห็นได้ ผู้ใช้จึงมักจะโต้ตอบกับการแจ้งเตือน (โดยการกด) ลักษณะการทำงานเริ่มต้นทั้งใน Android และ iOS คือการเปิดแอปพลิเคชัน หากแอปพลิเคชันสิ้นสุดลง ระบบจะเริ่มต้นแอปพลิเคชัน หากแอปพลิเคชันอยู่ในเบื้องหลัง ระบบจะนำแอปพลิเคชันขึ้นมาแสดงในเบื้องหน้า

คุณอาจต้องการจัดการการโต้ตอบของผู้ใช้เมื่อแอปพลิเคชันเปิดขึ้น ทั้งนี้ขึ้นอยู่กับเนื้อหาของการแจ้งเตือน เช่น หากมีการส่งข้อความแชทใหม่ผ่านการแจ้งเตือนและผู้ใช้กดการแจ้งเตือนนั้น คุณอาจต้องการเปิดการสนทนาที่เฉพาะเจาะจงเมื่อแอปพลิเคชันเปิดขึ้น

แพ็กเกจ firebase-messaging มีวิธีจัดการการโต้ตอบนี้ 2 วิธี ดังนี้

  • getInitialMessage(): หากเปิดแอปพลิเคชันจากสถานะที่สิ้นสุดแล้ว ระบบจะแสดงผล Future ที่มี RemoteMessage เมื่อใช้แล้ว ระบบจะนำ RemoteMessage ออก
  • onMessageOpenedApp: Stream ซึ่งโพสต์ RemoteMessage เมื่อเปิดแอปพลิเคชันจากสถานะเบื้องหลัง

เราขอแนะนำให้จัดการทั้ง 2 สถานการณ์เพื่อให้ผู้ใช้ได้รับ UX ที่ราบรื่น ตัวอย่างโค้ดด้านล่างแสดงวิธีดำเนินการนี้

class Application extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _Application();
}

class _Application extends State<Application> {
  // It is assumed that all messages contain a data field with the key 'type'
  Future<void> setupInteractedMessage() async {
    // Get any messages which caused the application to open from
    // a terminated state.
    RemoteMessage? initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();

    // If the message also contains a data property with a "type" of "chat",
    // navigate to a chat screen
    if (initialMessage != null) {
      _handleMessage(initialMessage);
    }

    // Also handle any interaction when the app is in the background via a
    // Stream listener
    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
  }

  void _handleMessage(RemoteMessage message) {
    if (message.data['type'] == 'chat') {
      Navigator.pushNamed(context, '/chat',
        arguments: ChatArguments(message),
      );
    }
  }

  @override
  void initState() {
    super.initState();

    // Run code required to handle interacted messages in an async function
    // as initState() must not be async
    setupInteractedMessage();
  }

  @override
  Widget build(BuildContext context) {
    return Text("...");
  }
}

วิธีจัดการการโต้ตอบจะขึ้นอยู่กับการตั้งค่าแอปพลิเคชัน ตัวอย่างข้างต้นแสดงภาพพื้นฐานโดยใช้ StatefulWidget

แปลข้อความ

คุณส่งสตริงที่แปลแล้วได้ 2 วิธี ดังนี้

  • จัดเก็บภาษาที่ต้องการของผู้ใช้แต่ละรายในเซิร์ฟเวอร์และส่งการแจ้งเตือนที่ปรับแต่งแล้วสำหรับแต่ละภาษา
  • ฝังสตริงที่แปลแล้วในแอปและใช้การตั้งค่าภาษาดั้งเดิมของระบบปฏิบัติการ

วิธีใช้ตัวเลือกที่ 2 มีดังนี้

Android

  1. ระบุข้อความภาษาเริ่มต้นใน resources/values/strings.xml ดังนี้

    <string name="notification_title">Hello world</string>
    <string name="notification_message">This is a message</string>
    
  2. ระบุข้อความที่แปลในไดเรกทอรี values-language เช่น ระบุข้อความภาษาฝรั่งเศสใน resources/values-fr/strings.xml

    <string name="notification_title">Bonjour le monde</string>
    <string name="notification_message">C'est un message</string>
    
  3. ในเพย์โหลดของเซิร์ฟเวอร์ ให้ใช้คีย์ title_loc_key และ body_loc_key สำหรับข้อความที่แปลแล้วแทนการใช้คีย์ title, message และ body แล้วตั้งค่าคีย์ดังกล่าวเป็นแอตทริบิวต์ name ของข้อความที่ต้องการแสดง

    เพย์โหลดของข้อความจะมีลักษณะดังนี้

    {
      "android": {
         "notification": {
           "title_loc_key": "notification_title",
           "body_loc_key": "notification_message"
         }
      }
    }
    

iOS

  1. ระบุข้อความภาษาเริ่มต้นใน Base.lproj/Localizable.strings ดังนี้

    "NOTIFICATION_TITLE" = "Hello World";
    "NOTIFICATION_MESSAGE" = "This is a message";
    
  2. ระบุข้อความที่แปลในไดเรกทอรี language.lproj เช่น ระบุข้อความภาษาฝรั่งเศสใน fr.lproj/Localizable.strings

    "NOTIFICATION_TITLE" = "Bonjour le monde";
    "NOTIFICATION_MESSAGE" = "C'est un message";
    

    เพย์โหลดของข้อความจะมีลักษณะดังนี้

    {
      "apns": {
         "payload": {
           "alert": {
             "title-loc-key": "NOTIFICATION_TITLE",
             "loc-key": "NOTIFICATION_MESSAGE"
           }
         }
      }
    }
    

เปิดใช้การส่งออกข้อมูลการนำส่งข้อความ

คุณสามารถส่งออกข้อมูลข้อความไปยัง BigQuery เพื่อวิเคราะห์เพิ่มเติมได้ BigQuery ช่วยให้คุณวิเคราะห์ข้อมูลโดยใช้ BigQuery SQL ส่งออกไปยังผู้ให้บริการคลาวด์รายอื่น หรือใช้ข้อมูลสําหรับโมเดล ML ที่กําหนดเองได้ การส่งออกไปยัง BigQuery รวมข้อมูลทั้งหมดที่ใช้ได้สำหรับข้อความ ไม่ว่าจะเป็นข้อความประเภทใดหรือส่งผ่าน API หรือเครื่องมือแต่งการแจ้งเตือนก็ตาม

หากต้องการเปิดใช้การส่งออก ให้ทำตามขั้นตอนที่อธิบายไว้ที่นี่ก่อน จากนั้นทำตามวิธีการต่อไปนี้

Android

คุณใช้โค้ดต่อไปนี้ได้

await FirebaseMessaging.instance.setDeliveryMetricsExportToBigQuery(true);

iOS

สำหรับ iOS คุณต้องเปลี่ยน AppDelegate.m ด้วยเนื้อหาต่อไปนี้

#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import <Firebase/Firebase.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  [[FIRMessaging extensionHelper] exportDeliveryMetricsToBigQueryWithMessageInfo:userInfo];
}

@end

เว็บ

สำหรับเว็บ คุณต้องเปลี่ยน Service Worker เพื่อใช้ SDK เวอร์ชัน v9 คุณต้องรวมเวอร์ชัน v9 ไว้ด้วยกัน ดังนั้นคุณจึงต้องใช้ Bundler เช่น esbuild เป็นต้น เพื่อให้ Service Worker ทำงานได้ ดูแอปตัวอย่างเพื่อดูวิธีดำเนินการ

เมื่อย้ายข้อมูลไปยัง SDK เวอร์ชัน 9 แล้ว คุณจะใช้โค้ดต่อไปนี้ได้

import {
  experimentalSetDeliveryMetricsExportedToBigQueryEnabled,
  getMessaging,
} from 'firebase/messaging/sw';
...

const messaging = getMessaging(app);
experimentalSetDeliveryMetricsExportedToBigQueryEnabled(messaging, true);

อย่าลืมเรียกใช้ yarn build เพื่อส่งออก Service Worker เวอร์ชันใหม่ไปยังโฟลเดอร์ web

แสดงรูปภาพในการแจ้งเตือนบน iOS

ในอุปกรณ์ Apple หากต้องการให้การแจ้งเตือน FCM ขาเข้าแสดงรูปภาพจากเพย์โหลด FCM คุณต้องเพิ่มส่วนขยายบริการการแจ้งเตือนเพิ่มเติมและกำหนดค่าแอปให้ใช้ส่วนขยายดังกล่าว

หากใช้การตรวจสอบสิทธิ์ทางโทรศัพท์ของ Firebase คุณต้องเพิ่ม Pod ของ Firebase Auth ลงใน Podfile

ขั้นตอนที่ 1 - เพิ่มส่วนขยายบริการแจ้งเตือน

  1. ใน Xcode ให้คลิก File > New > Target...
  2. โมดอลจะแสดงรายการเป้าหมายที่เป็นไปได้ ให้เลื่อนลงหรือใช้ตัวกรองเพื่อเลือกส่วนขยายบริการการแจ้งเตือน คลิกถัดไป
  3. เพิ่มชื่อผลิตภัณฑ์ (ใช้ "ImageNotification" เพื่อทำตามบทแนะนำนี้) เลือก Swift หรือ Objective-C แล้วคลิกเสร็จสิ้น
  4. เปิดใช้รูปแบบโดยคลิกเปิดใช้งาน

ขั้นตอนที่ 2 - เพิ่มเป้าหมายลงใน Podfile

Swift

ตรวจสอบว่าส่วนขยายใหม่มีสิทธิ์เข้าถึงแพ็กเกจ FirebaseMessaging swift โดยเพิ่มลงในRunnerเป้าหมาย

  1. จากแถบนำทาง ให้เพิ่ม Firebase SDK สำหรับแพลตฟอร์ม Apple โดยไปที่File > Add Package Dependencies...

  2. ค้นหาหรือป้อน URL ของแพ็กเกจ https://github.com/firebase/firebase-ios-sdk

  3. เพิ่มลงในโปรเจ็กต์ Runner: เพิ่มแพ็กเกจ

  4. เลือก FirebaseMessaging แล้วเพิ่มลงใน ImageNotification เป้าหมาย: Add Package

Objective-C

ตรวจสอบว่าส่วนขยายใหม่มีสิทธิ์เข้าถึงพ็อด Firebase/Messaging โดยเพิ่มพ็อดใน Podfile ดังนี้

  1. เปิด Podfile จาก Navigator โดยไปที่ Pods > Podfile

  2. เลื่อนลงไปที่ด้านล่างของไฟล์ แล้วเพิ่มข้อความต่อไปนี้

    target 'ImageNotification' do
      use_frameworks!
      pod 'Firebase/Auth' # Add this line if you are using FirebaseAuth phone authentication
      pod 'Firebase/Messaging'
    end
    
  3. ติดตั้งหรืออัปเดตพ็อดโดยใช้ pod install จากไดเรกทอรี ios หรือ macos

ขั้นตอนที่ 3 - ใช้ตัวช่วยส่วนขยาย

ณ จุดนี้ ทุกอย่างควรยังคงทำงานตามปกติ ขั้นตอนสุดท้ายคือการเรียกใช้ตัวช่วยส่วนขยาย

Swift

  1. เลือกส่วนขยาย ImageNotification จากแถบนำทาง

  2. เปิดไฟล์ NotificationService.swift

  3. แทนที่เนื้อหาของ NotificationService.swift ด้วย

    import UserNotifications
    import FirebaseMessaging
    
    class NotificationService: UNNotificationServiceExtension {
    
        var contentHandler: ((UNNotificationContent) -> Void)?
        var bestAttemptContent: UNMutableNotificationContent?
    
        override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
            self.contentHandler = contentHandler
            bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
    
            Messaging.serviceExtension().populateNotificationContent(bestAttemptContent!, withContentHandler: contentHandler)
        }
    
        override func serviceExtensionTimeWillExpire() {
            if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
                contentHandler(bestAttemptContent)
            }
        }
    }
    

Objective-C

  1. เลือกส่วนขยาย ImageNotification จากแถบนำทาง

  2. เปิดไฟล์ NotificationService.m

  3. ที่ด้านบนของไฟล์ ให้นำเข้า FirebaseMessaging.h ทันทีหลังจาก NotificationService.h ดังที่แสดงด้านล่าง

    แทนที่เนื้อหาของ NotificationService.m ด้วย

    #import "NotificationService.h"
    #import "FirebaseMessaging.h"
    #import <FirebaseAuth/FirebaseAuth-Swift.h> // Add this line if you are using FirebaseAuth phone authentication
    #import <UIKit/UIKit.h> // Add this line if you are using FirebaseAuth phone authentication
    
    @interface NotificationService () <NSURLSessionDelegate>
    
    @property(nonatomic) void (^contentHandler)(UNNotificationContent *contentToDeliver);
    @property(nonatomic) UNMutableNotificationContent *bestAttemptContent;
    
    @end
    
    @implementation NotificationService
    
    /* Uncomment this if you are using Firebase Auth
    - (BOOL)application:(UIApplication *)app
                openURL:(NSURL *)url
                options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
      if ([[FIRAuth auth] canHandleURL:url]) {
        return YES;
      }
      return NO;
    }
    
    - (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
      for (UIOpenURLContext *urlContext in URLContexts) {
        [FIRAuth.auth canHandleURL:urlContext.URL];
      }
    }
    */
    
    - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
        self.contentHandler = contentHandler;
        self.bestAttemptContent = [request.content mutableCopy];
    
        // Modify the notification content here...
        [[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];
    }
    
    - (void)serviceExtensionTimeWillExpire {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        self.contentHandler(self.bestAttemptContent);
    }
    
    @end
    

ขั้นตอนที่ 4 - เพิ่มรูปภาพลงในเพย์โหลด

ตอนนี้คุณเพิ่มรูปภาพในเพย์โหลดการแจ้งเตือนได้แล้ว ดูเอกสารประกอบของ iOS เกี่ยวกับวิธีสร้างคำขอส่ง โปรดทราบว่าอุปกรณ์จะบังคับใช้ขนาดรูปภาพสูงสุด 300 KB