📦 SwiftyLaunch Modules
⚙️ BackendKit
NotifKit Integration

NotifKit Integration in BackendKit

NotifKit Integration

Send push notifications to your users using our pre-built NotifKit functions.

Basic Usage

Import NotifKit

To use NotifKit functions, you first need to include PushNotifications in your file.

import * as PushNotifications from "./NotifKit/PushNotifications";

Function Definition

Now you can send a push notification to a user in backend code using the sendNotificationToUserWithID function.

PushNotifications.ts
export async function sendNotificationToUserWithID({
  userID,
  data,
}: {
  userID: string;
  data: NotificationReadableData;
}) {}
  • userID: The ID of the user. Set to be the same as Firebase User ID when the user authenticates on the client-side. Pass OneSignal User ID if you want to send a push notification for a specific user that is not the currently authenticated user.
  • data: The data of the notification. (See definition below)

Notification Readable Data Definition

PushNotifications.ts
export type NotificationReadableData = {
  title: string;
  message: string;
  additionalData?: InAppNotificationAdditionalData;
};
  • title: The title of the notification.
  • message: The message of the notification.
  • additionalData (Optional): Additional data that can be sent with the notification. If not undefined, will show the notification as an in-app notification using the passed data if the application is open (See definition below)

Additional In-App Notification Data Definition

Data that is used to show an in-app notification, if the app is open during a push notification and you wish for the push notification to be able to be shown as an in-app notification (Routing Push Notifications to In-App Notifications).

PushNotifications.ts
type InAppNotificationAdditionalData = {
  inAppSymbol: SFSymbol; // Symbol to show in the in-app notification
  inAppColor: string; //in HEX
  inAppSize?: "normal" | "compact"; //defaults to normal
  inAppHaptics?: "success" | "warning" | "error"; // defaults to warning
};

Usage Example

On the Backend

This example shows a backend function that sends a push notification to a user with a message with params:

  • userID: The ID of the user to send the notification to.
  • message: The message to send in the notification.
export const sendNotificationTo = onCall(async (request) => {
  let fromUid = request.auth?.uid;
  // ...
  try {
    if (!fromUid) {
      throw new Error("User Not Logged In");
    }
 
    // get current user data
    const user = await getAuth().getUser(fromUid);
 
    // get receiver user ID from request
    let toUid = request.data?.userID as string;
    if (!toUid) {
      // ...
      throw new Error("No Receiver UserID provided");
    }
 
    // get message from request, if not available, set to "Empty Message"
    let message = request.data?.message as string | "Empty Message";
 
    // send notification to the user
    await PushNotifications.sendNotificationToUserWithID({
      userID: toUid,
      data: {
        title: `Message from ${user.displayName || fromUid}`,
        message: message,
        additionalData: {
          // show in-app notification with these params if app is open
          inAppSymbol: "bolt.fill",
          inAppColor: "#ae0000",
          inAppSize: "compact",
          inAppHaptics: "error",
        },
      },
    });
    // ...
  } catch (error) {
    // ...
    throw new Error("Server Error");
  }
  return true;
});

On the Client

This button in the BackendFunctionsExampleView sends a push notification to a user with the message entered in the alert.

BackendFunctionsExampleView.swift
struct SendNotificationButton: View {
 
    @EnvironmentObject var db: DB
    @State var showMessageInputAlert = false
    @State var notifMessage = "Hello there!"
    let userID: String
 
    var body: some View {
        Button(
            action: {
                showMessageInputAlert = true
            },
            label: /* Label */
        )
        .alert("Enter your Message", isPresented: $showMessageInputAlert) {
            // ... Textfield
            Button("OK") {
                Task {
                    await db.executeIfSignedIn(
                        otherwise: .showInAppNotification,
                        {
                            await db.sendNotificationTo(userID: userID, message: notifMessage)
                        })
                }
            }
            // ... cancel button
        }
 
    }
}

Here's the BackendFunctions.swift part of code that calls the backend function to send the notification:

BackendFunctions.swift
extension DB {
  	public func sendNotificationTo(userID: String, message: String) async {
      // ...
      do {
        var contentDict: [String: Any] = ["userID": userID]
        contentDict["message"] = message
        let _ = try await functions.httpsCallable("sendNotificationTo").call(contentDict)
      } catch {
        // ...
        showInAppNotification(.error, content: /* ERROR MESSAGE */)
      }
	}
}