Nhận tin nhắn trong ứng dụng của Apple

Sau khi được cài đặt trên một thiết bị, ứng dụng khách của bạn có thể nhận thông báo qua giao diện APN FCM. Bạn có thể ngay lập tức bắt đầu gửi thông báo đến phân khúc người dùng bằng Trình soạn thông báo hoặc các thông báo được tạo trên máy chủ ứng dụng của bạn.

Xử lý thông báo cảnh báo

FCM cung cấp tất cả thông báo nhắm mục tiêu đến các ứng dụng của Apple thông qua APN. Để tìm hiểu thêm về cách nhận thông báo APN qua UNUserNotificationCenter, hãy xem tài liệu của Apple về Xử lý thông báo và hành động liên quan đến thông báo.

Bạn phải đặt uỷ quyền UNUserNotificationCenter và triển khai các phương thức uỷ quyền thích hợp để nhận thông báo hiển thị từ FCM.

Swift


extension AppDelegate: UNUserNotificationCenterDelegate {
  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification) async
    -> UNNotificationPresentationOptions {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // ...

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    return [[.alert, .sound]]
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse) async {
    let userInfo = response.notification.request.content.userInfo

    // ...

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print full message.
    print(userInfo)
  }
}

Objective-C

// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler();
}

Nếu bạn muốn thêm thao tác tuỳ chỉnh vào thông báo của mình, hãy đặt tham số click_action trong tải trọng thông báo. Sử dụng giá trị mà bạn sẽ dùng cho khoá category trong tải trọng APN. Bạn phải đăng ký thao tác tuỳ chỉnh trước khi có thể sử dụng. Để biết thêm thông tin, hãy xem Hướng dẫn lập trình thông báo cục bộ và từ xa của Apple.

Để biết thông tin chi tiết về quá trình gửi tin nhắn đến ứng dụng của bạn, hãy xem Trang tổng quan báo cáo FCM. Trang tổng quan này ghi lại số lượng tin nhắn được gửi và mở trên các thiết bị của Apple và Android, cùng với dữ liệu về "lượt hiển thị" (thông báo mà người dùng nhìn thấy) cho các ứng dụng Android.

Xử lý thông báo đẩy im lặng

Khi gửi tin nhắn bằng phím content-available (tương đương với content-available của APN, tin nhắn sẽ được gửi dưới dạng thông báo im lặng, đánh thức ứng dụng của bạn trong nền để thực hiện các tác vụ như làm mới dữ liệu nền. Không giống như thông báo trên nền trước, các thông báo này phải được xử lý thông qua phương thức application(_:didReceiveRemoteNotification:fetchCompletionHandler:).

Triển khai application(_:didReceiveRemoteNotification:fetchCompletionHandler:) như sau:

Swift

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  return UIBackgroundFetchResult.newData
}

Objective-C

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}

Các nền tảng của Apple không đảm bảo việc gửi các thông báo trong nền. Để tìm hiểu về các điều kiện có thể khiến thông báo trong nền không hoạt động, hãy xem tài liệu của Apple về Đẩy cập nhật ở chế độ nền cho ứng dụng.

Diễn giải tải trọng tin nhắn thông báo

Tải trọng của thông báo thông báo là một từ điển gồm các khoá và giá trị. Các thông báo gửi qua APN tuân theo định dạng tải trọng của APN như dưới đây:

  {
    "aps" : {
      "alert" : {
        "body" : "great match!",
        "title" : "Portugal vs. Denmark",
      },
      "badge" : 1,
    },
    "customKey" : "customValue"
  }

Xử lý thông báo khi tắt phương thức xoáy

Theo mặc định, nếu bạn chỉ định lớp uỷ quyền ứng dụng của ứng dụng cho các thuộc tính uỷ quyền UNUserNotificationCenterMessaging, FCM sẽ tạo nhanh lớp uỷ quyền ứng dụng để tự động liên kết mã thông báo FCM của bạn với mã thông báo APN của thiết bị và chuyển các sự kiện đã nhận được thông báo đến Analytics. Nếu bạn thể hiện rõ việc tắt nhanh phương thức, nếu bạn đang tạo ứng dụng SwiftUI hoặc nếu bạn sử dụng một lớp riêng cho một trong hai tác vụ uỷ quyền, thì bạn sẽ cần thực hiện cả hai tác vụ này theo cách thủ công.

Để liên kết mã thông báo FCM với mã thông báo APN của thiết bị, hãy chuyển mã thông báo APN đến lớp Messaging trong trình xử lý làm mới mã thông báo của ủy quyền ứng dụng thông qua thuộc tính apnsToken.

Swift

func application(_ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  Messaging.messaging().apnsToken = deviceToken;
}
 

Objective-C

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [FIRMessaging messaging].APNSToken = deviceToken;
}

Để chuyển thông tin về biên nhận nhận thông báo đến Analytics, hãy sử dụng phương thức appDidReceiveMessage(_:).

Swift

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  let userInfo = notification.request.content.userInfo

  Messaging.messaging().appDidReceiveMessage(userInfo)

  // Change this to your preferred presentation option
  completionHandler([[.alert, .sound]])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
  let userInfo = response.notification.request.content.userInfo

  Messaging.messaging().appDidReceiveMessage(userInfo)

  completionHandler()
}

func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
   fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  Messaging.messaging().appDidReceiveMessage(userInfo)
  completionHandler(.noData)
}

Objective-C

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;

  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  completionHandler();
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
  completionHandler(UIBackgroundFetchResultNoData);
}