registerPushToken method

Future<PushTokenRegistrationStatus> registerPushToken({
  1. required PushTokenType type,
  2. required String token,
  3. bool alwaysPush = false,
  4. bool unique = false,
})

Registers push token with type.

In order to make push notification work with sendbird, token has to be registered with specific PushTokenType such as fcm or apns. If unique is true then only one push token will be keep tracked Make sure to pass token that is for the specific PushTokenType

Implementation

Future<PushTokenRegistrationStatus> registerPushToken({
  required PushTokenType type,
  required String token,
  bool alwaysPush = false,
  bool unique = false,
}) async {
  try {
    //* Check if device token exists in shared preference
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String>? cachedToken = prefs.getStringList(prefDeviceToken);

    if (cachedToken != null && cachedToken.contains(token)) {
      //? If unique true then only one token will be registered
      if (unique == false) {
        logger.d('Token already registered');
        return PushTokenRegistrationStatus.success; // or appropriate status
      }
    }

    int? deviceTokenLastDeletedAt =
        await _int.api.send<int?>(UserPushTokenRegisterRequest(
      type: type,
      token: token,
      alwaysPush: alwaysPush,
      unique: unique,
    ));

    //* If deviceTokenLastDeletedAt is not NULL then update the state
    if (deviceTokenLastDeletedAt != null) {
      await prefs.setInt(
        prefDeviceTokenLastDeletedAt,
        deviceTokenLastDeletedAt,
      );
    }

    //* Store status in sharedpreference
    //? If unique true then only one token will be registered
    if (unique == true) {
      logger.d('RegisterPushToken `Unique` Called - Token registering');
      List<String> uniqueTokenList = [token];
      await prefs.setStringList(prefDeviceToken, uniqueTokenList);
    } else {
      // read the old list
      List<String>? formerSavedList = prefs.getStringList(prefDeviceToken);

      // append the new data to it
      if (formerSavedList != null) {
        formerSavedList.add(token);
      } else {
        formerSavedList = [token];
      }

      // and save the new list back to storage
      await prefs.setStringList(prefDeviceToken, formerSavedList);
    }

    return PushTokenRegistrationStatus.success;
  } catch (exception) {
    logger.e(StackTrace.current, "Failed to register push token");
    rethrow;
  }
}