> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 示例应用：SDK 设置和用户身份

> 示例应用 Clean Beans 如何在 Expo 中安装 OneSignal SDK、通过 External ID 将每台设备关联到用户，并添加邮件渠道。

本页面是[示例应用：完整的 OneSignal 集成](https://documentation.onesignal.com/docs/cn/example-full-integration-overview.md)的一部分，该指南从头到尾跟随一个真实应用。这个应用是 **Clean Beans**，一款面向合租家庭的打扫值日表应用，使用 Expo（React Native）和 Supabase 后端构建。

其他所有功能都取决于四件事是否正确：SDK 已安装，SDK 随应用启动，每台设备都关联到一个用户，以及用户可以控制自己接收的内容。

## 使用 Expo 插件安装 \\

`onesignal-expo-plugin` 会在构建时配置原生 iOS 和 Android 项目。它会添加 OneSignal 在图片、角标和送达确认方面所需的推送 capability、App Group 和 Notification Service Extension。

```json app.json theme={null}
{
  "expo": {
    "plugins": [
      ["onesignal-expo-plugin", { "mode": "production" }],
      "expo-router",
      "./plugins/withLiveActivityWidget"
    ],
    "ios": {
      "bundleIdentifier": "com.onesignal.cleaningapp",
      "infoPlist": {
        "UIBackgroundModes": ["remote-notification"],
        "NSSupportsLiveActivities": true
      },
      "entitlements": {
        "aps-environment": "production",
        "com.apple.security.application-groups": [
          "group.com.onesignal.cleaningapp.onesignal"
        ]
      }
    }
  }
}
```

## 在根布局中初始化一次 \\

Clean Beans 在根布局中初始化 OneSignal，因此每次启动时都会在任何界面出现之前运行一次。

```typescript app/_layout.tsx theme={null}
// Verbose logging is for debugging during the beta. Remove it, or lower
// the level, before a public release.
OneSignal.Debug.setLogLevel(LogLevel.Verbose);
OneSignal.initialize('YOUR_ONESIGNAL_APP_ID');
OneSignal.Notifications.requestPermission(true);
```

> [!TIP]
>
> 在首次启动时请求权限是最简单的方法。若要先说明好处，请在系统提示之前显示一条应用内消息。Clean Beans 已经准备好了一条：请参阅[推送权限预提示](https://documentation.onesignal.com/docs/cn/example-full-integration-in-app-messages.md#push-permission-pre-prompt)。

## 将每台设备关联到用户 \\

用户登录时，应用会将其 Supabase 用户 ID 传给 `OneSignal.login()`。这个 ID 就成为 External ID。用户退出登录时，`logout()` 会解除设备关联，这样下一个登录的人不会继承前一个用户的消息。

```typescript app/_layout.tsx theme={null}
// Link OneSignal identity to authenticated user and sync timezone
//
// Wait until the saved session has been restored. On a cold start `user`
// is null for a moment while it loads; calling logout() then, followed by
// login() a moment later, can leave this device's push subscription on an
// anonymous OneSignal user, so pushes sent to the External ID never reach
// the phone. logout() is only called on a real sign-out.
const wasSignedIn = useRef(false);
useEffect(() => {
  if (loading) return;

  if (user) {
    wasSignedIn.current = true;
    OneSignal.login(user.id);
    syncDeviceTimezone();
    // Add email subscription and sync data tags to OneSignal
    if (user.email) syncOneSignalEmail(user.email);
    // Add the SMS subscription if the user has a verified phone number
    syncOneSignalSms();
    syncOneSignalTags();
  } else if (wasSignedIn.current) {
    wasSignedIn.current = false;
    OneSignal.logout();
  }
}, [user, loading]);
```

> [!WARNING]
>
> 调用任一方法之前，请等待已保存的会话加载完成。冷启动时，已登录用户会短暂处于未知状态。如果应用在此时调用 `logout()`，稍后又调用 `login()`，设备的推送订阅可能会留在一个匿名用户上，发送到 External ID 的推送将无法到达手机。只有在用户真正退出登录时才调用 `logout()`。

正是这一次调用，让本指南中的每次后端发送成为可能。知道用户数据库 ID 的函数无需了解其设备的任何信息，就能向其发送消息。

## 添加邮件渠道 \\

应用在注册时就已获知每位用户的邮箱地址，因此会在登录时将其注册为邮件订阅。OneSignal 会忽略使用相同地址的重复调用。

```typescript src/lib/onesignalSync.ts theme={null}
export function syncOneSignalEmail(email: string): void {
  try {
    if (!email) return;
    OneSignal.User.addEmail(email);
    console.log('[onesignalSync] Email subscription added');
  } catch (e) {
    console.warn('[onesignalSync] syncOneSignalEmail error:', e);
  }
}
```

短信也以同样方式通过 `addSms()` 添加，但只在号码验证之后添加。请参阅[短信：验证码和邀请](https://documentation.onesignal.com/docs/cn/example-full-integration-sms.md)。

## 让用户控制接收的内容 \\

通知设置界面有一个总开关，以及每种消息类型各一个开关。

![包含总开关和按类型开关的通知设置界面](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-notifications.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=57fef32f8987a51e7bdf8c40a6273087)

通知设置：总开关、按类型的开关和每日提醒时间。

总开关会在推送订阅上调用 `optOut()` 和 `optIn()`，从而让 OneSignal 停止和恢复向该设备投递。

```typescript app/notification-settings.tsx theme={null}
const handlePushMasterToggle = async (enabled: boolean) => {
  try {
    if (enabled) {
      OneSignal.User.pushSubscription.optIn();
    } else {
      OneSignal.User.pushSubscription.optOut();
    }
  } catch (e) {
    console.warn('OneSignal subscription toggle failed:', e);
  }
  save({ ...prefs, pushEnabled: enabled });
};
```

每个开关也会保存到用户的资料行中。后端在发送任何内容之前都会读取这些列，按类型的偏好就是这样生效的。

```typescript src/lib/database.ts theme={null}
  const { error } = await supabase
    .from('profiles')
    .update({
      notifications_enabled: prefs.pushEnabled,
      push_daily_reminders: prefs.pushDailyReminders,
      push_streak_reminders: prefs.pushStreakReminders,
      push_cleaning_done: prefs.pushCleaningDone,
      push_leaderboard_updates: prefs.pushLeaderboardUpdates,
      push_upcoming_cleaning: prefs.pushUpcomingCleaning,
      push_overdue_reminders: prefs.pushOverdueReminders,
      email_weekly_summary: prefs.emailWeeklySummary,
      notification_hour: prefs.notificationHour,
      timezone: prefs.timezone,
    })
    .eq('id', user.id);
```

> [!NOTE]
>
> 将偏好存储在您自己的数据库中，并在每次发送前检查，可以把逻辑集中在一个地方。另一种做法是将偏好存储为标签，并在 OneSignal 中按标签筛选。当您向细分发送消息时，这种方式很合适。Clean Beans 向特定用户发送，因此检查数据库更简单。

> [card] [移动 SDK 参考](https://documentation.onesignal.com/docs/cn/mobile-sdk-reference.md)
>
> 本指南中使用的所有客户端方法。

> [card] [用户和 External ID](https://documentation.onesignal.com/docs/cn/users.md)
>
> 身份如何跨渠道和设备关联订阅。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.