首页指南参考教程

Expo 通知 iconExpo 通知

GitHub

npm

一个库,提供 API 来获取推送通知令牌并渲染、安排、接收和响应通知。

Web

expo-notifications 提供了一个 API 来获取推送通知令牌并渲染、安排、接收和响应通知。

¥expo-notifications provides an API to fetch push notification tokens and to present, schedule, receive and respond to notifications.

特性

¥Features

  • 安排在特定日期或从现在起的某个时间发出一次性通知

    ¥Schedule a one-off notification for a specific date or some time from now

  • 安排通知在某个时间间隔内重复(或 iOS 上的日历日期匹配)

    ¥Schedule a notification repeating in some time interval (or a calendar date match on iOS)

  • 获取和设置应用徽章图标编号

    ¥Get and set the application badge icon number

  • 获取原生设备推送令牌,以便你可以使用 FCM 和 APN 发送推送通知

    ¥Fetch a native device push token, so you can send push notifications with FCM and APNs

  • 获取 Expo 推送令牌,以便你可以使用 Expo 发送推送通知

    ¥Fetch an Expo push token, so you can send push notifications with Expo

  • 在前台和后台收听传入的通知

    ¥Listen to incoming notifications in the foreground and background

  • 聆听与通知的交互

    ¥Listen to interactions with notifications

  • 当应用位于前台时处理通知

    ¥Handle notifications when the app is in the foreground

  • 强制关闭通知中心/托盘中的通知

    ¥Imperatively dismiss notifications from Notification Center/tray

  • 创建、更新和删除 Android 通知渠道

    ¥Create, update, and delete Android notification channels

  • 在 Android 上设置通知的自定义图标和颜色

    ¥Set custom icon and color for notifications on Android

安装

¥Installation

Terminal
npx expo install expo-notifications

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

用法

¥Usage

查看下面的示例 Snack 以了解通知的实际效果,请确保使用物理设备进行测试。推送通知不适用于模拟器/模拟器。

¥Check out the example Snack below to see Notifications in action, make sure to use a physical device to test it. Push notifications don't work on emulators/simulators.

Push Notifications
import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState('');
  const [channels, setChannels] = useState<Notifications.NotificationChannel[]>(
    [],
  );
  const [notification, setNotification] = useState<
    Notifications.Notification | undefined
  >(undefined);
  const notificationListener = useRef<Notifications.Subscription>();
  const responseListener = useRef<Notifications.Subscription>();

  useEffect(() => {
    registerForPushNotificationsAsync().then(
      (token) => token && setExpoPushToken(token),
    );

    if (Platform.OS === 'android') {
      Notifications.getNotificationChannelsAsync().then((value) =>
        setChannels(value ?? []),
      );
    }
    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log(response);
      });

    return () => {
      notificationListener.current &&
        Notifications.removeNotificationSubscription(
          notificationListener.current,
        );
      responseListener.current &&
        Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'space-around',
      }}
    >
      <Text>Your expo push token: {expoPushToken}</Text>
      <Text>{`Channels: ${JSON.stringify(
        channels.map((c) => c.id),
        null,
        2,
      )}`}</Text>
      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
        <Text>
          Title: {notification && notification.request.content.title}{' '}
        </Text>
        <Text>Body: {notification && notification.request.content.body}</Text>
        <Text>
          Data:{' '}
          {notification && JSON.stringify(notification.request.content.data)}
        </Text>
      </View>
      <Button
        title="Press to schedule a notification"
        onPress={async () => {
          await schedulePushNotification();
        }}
      />
    </View>
  );
}

async function schedulePushNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: "You've got mail! 📬",
      body: 'Here is the notification body',
      data: { data: 'goes here', test: { test1: 'more data' } },
    },
    trigger: { seconds: 2 },
  });
}

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } =
      await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    // Learn more about projectId:
    // https://expo.nodejs.cn/push-notifications/push-notifications-setup/#configure-projectid
    // EAS projectId is used here.
    try {
      const projectId =
        Constants?.expoConfig?.extra?.eas?.projectId ??
        Constants?.easConfig?.projectId;
      if (!projectId) {
        throw new Error('Project ID not found');
      }
      token = (
        await Notifications.getExpoPushTokenAsync({
          projectId,
        })
      ).data;
      console.log(token);
    } catch (e) {
      token = `${e}`;
    }
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

向用户渲染通知

¥Present the notification to the user

import * as Notifications from 'expo-notifications';

// First, set the handler that will cause the notification
// to show the alert

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

// Second, call the method

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Look at that notification',
    body: "I'm so proud of myself!",
  },
  trigger: null,
});

通过导航处理推送通知

¥Handle push notifications with navigation

如果你想在收到推送通知时深层链接到应用中的特定屏幕,你可以配置 Expo 的任一导航系统来执行此操作。

¥If you'd like to deep link to a specific screen in your app when you receive a push notification, you can configure either of Expo's navigation systems to do that.

你可以使用 Expo Router 的 内置深度链接 来处理来自推送通知的传入 URL。只需配置根布局即可监听传入和初始通知事件。

¥You can use Expo Router's built-in deep linking to handle incoming URLs from push notifications. Simply configure the root layout to listen for incoming and initial notification events.

app/_layout.tsx
import { useEffect } from 'react';
import * as Notifications from 'expo-notifications';
import { router } from 'expo-router';

function useNotificationObserver() {
  useEffect(() => {
    let isMounted = true;

    function redirect(notification: Notifications.Notification) {
      const url = notification.request.content.data?.url;
      if (url) {
        router.push(url);
      }
    }

    Notifications.getLastNotificationResponseAsync()
      .then(response => {
        if (!isMounted || !response?.notification) {
          return;
        }
        redirect(response?.notification);
      });

    const subscription = Notifications.addNotificationResponseReceivedListener(response => {
      redirect(response.notification);
    });

    return () => {
      isMounted = false;
      subscription.remove();
    };
  }, []);
}

export default function Layout() {
  useNotificationObserver();

  return <Slot />;
}

React Navigation 的手册 链接配置 可以配置为处理来自推送通知的传入重定向:

¥React Navigation's manual linking configuration can be configured to handle incoming redirects from push notifications:

App.tsx
import React from 'react';
import { Linking } from 'react-native';
import * as Notifications from 'expo-notifications';
import { NavigationContainer } from '@react-navigation/native';

export default function App() {
  return (
    <NavigationContainer
      linking={{
        config: {
          // Configuration for linking
        },
        async getInitialURL() {
          // First, you may want to do the default deep link handling
          // Check if app was opened from a deep link
          const url = await Linking.getInitialURL();

          if (url != null) {
            return url;
          }

          // Handle URL from expo push notifications
          const response = await Notifications.getLastNotificationResponseAsync();

          return response?.notification.request.content.data.url;
        },
        subscribe(listener) {
          const onReceiveURL = ({ url }: { url: string }) => listener(url);

          // Listen to incoming links from deep linking
          const eventListenerSubscription = Linking.addEventListener('url', onReceiveURL);

          // Listen to expo push notifications
          const subscription = Notifications.addNotificationResponseReceivedListener(response => {
            const url = response.notification.request.content.data.url;

            // Any custom logic to see whether the URL needs to be handled
            //...

            // Let React Navigation handle the URL
            listener(url);
          });

          return () => {
            // Clean up the event listeners
            eventListenerSubscription.remove();
            subscription.remove();
          };
        },
      }}>
      

{/* Your app content */}


    </NavigationContainer>
  );
}

请参阅 React 导航文档 的更多详细信息。

¥See more details on React Navigation documentation.

配置

¥Configuration

证书

¥Credentials

安卓

¥Android

所有 Android 应用都需要 Firebase Cloud Messaging 凭据才能在应用中接收推送通知(在 Expo Go 中进行测试时除外)。有关更多信息,请参阅如何为你的应用获取 FCM 资质

¥Firebase Cloud Messaging credentials are required for all Android apps to receive push notifications in your app (except when testing in Expo Go). For more information, see how to get FCM credentials for your app.

iOS 系统

¥iOS

要注册你的 iOS 设备并自动为你的 EAS 版本启用推送通知,请参阅 推送通知设置

¥To register your iOS device and automatically enable push notifications for your EAS Build, see push notification setup.

应用配置

¥App config

要配置 expo-notifications,请在 EAS 构建npx expo run:[android|ios] 的应用配置(app.json 或 app.config.js)中使用内置 配置插件。该插件允许你配置以下无法在运行时设置并需要构建新的应用二进制文件才能生效的属性:

¥To configure expo-notifications, use the built-in config plugin in the app config (app.json or app.config.js) for EAS Build or with npx expo run:[android|ios]. The plugin allows you to configure the following properties that cannot be set at runtime and require building a new app binary to take effect:

Configurable properties

NameDefaultDescription
icon-Only for: 
Android

Local path to an image to use as the icon for push notifications. 96x96 all-white png with transparency.

color#ffffffOnly for: 
Android

Tint color for the push notification image when it appears in the notification tray.

sounds-

Array of local paths to sound files (.wav recommended) that can be used as custom notification sounds.

以下是在应用配置文件中使用配置插件的示例:

¥Here is an example of using the config plugin in the app config file:

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "icon": "./local/assets/notification-icon.png",
          "color": "#ffffff",
          "sounds": [
            "./local/assets/notification-sound.wav",
            "./local/assets/notification-sound-other.wav"
          ]
        }
      ]
    ]
  }
}
Are you using this library in a bare React Native app?

了解如何在 expo-notifications 存储库中的安装说明 文件中配置原生项目。

¥Learn how to configure the native projects in the installation instructions in the expo-notifications repository.

iOS APNs 权利始终设置为 'development'。Xcode 在存档期间自动将其更改为 'production'。了解更多

¥The iOS APNs entitlement is always set to 'development'. Xcode automatically changes this to 'production' during the archive. Learn more.

权限

¥Permissions

安卓

¥Android

  • 在 Android 上,此模块需要订阅设备启动的权限。它用于在设备(重新)启动时设置计划通知。RECEIVE_BOOT_COMPLETED 权限是通过库 AndroidManifest.xml 自动添加的。

    ¥On Android, this module requires permission to subscribe to the device boot. It's used to setup scheduled notifications when the device (re)starts. The RECEIVE_BOOT_COMPLETED permission is added automatically through the library AndroidManifest.xml.

  • 从 Android 12(API 级别 31)开始,为了安排在准确时间触发的通知,你需要将 <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> 添加到 AndroidManifest.xml 中。你可以阅读有关 准确的报警权限 的更多信息。

    ¥Starting from Android 12 (API level 31), to schedule the notification that triggers at the exact time, you need to add <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> to AndroidManifest.xml. You can read more about the exact alarm permission.

  • 在 Android 13 上,应用用户必须选择通过操作系统自动触发的权限提示来接收通知。至少创建一个通知通道后,才会出现此提示。必须在 getDevicePushTokenAsyncgetExpoPushTokenAsync 之前调用 setNotificationChannelAsync 才能获取推送令牌。你可以在 官方文档 中详细了解 Android 13 的新通知权限行为。

    ¥On Android 13, app users must opt-in to receive notifications via a permissions prompt automatically triggered by the operating system. This prompt will not appear until at least one notification channel is created. The setNotificationChannelAsync must be called before getDevicePushTokenAsync or getExpoPushTokenAsync to obtain a push token. You can read more about the new notification permission behavior for Android 13 in the official documentation.

Android PermissionDescription

RECEIVE_BOOT_COMPLETED

Allows an application to receive the Intent.ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.

Allows an application to receive the Intent.ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting. If you don't request this permission, you will not receive the broadcast at that time. Though holding this permission does not have any security implications, it can have a negative impact on the user experience by increasing the amount of time it takes the system to start and allowing applications to have themselves running without the user being aware of them. As such, you must explicitly declare your use of this facility to make that visible to the user.

SCHEDULE_EXACT_ALARM

Allows applications to use exact alarm APIs.

iOS 系统

¥iOS

无需使用说明,参见 通知相关权限

¥No usage description is required, see notification-related permissions.

通知事件监听器

¥Notification events listeners

通知事件包括传入通知、用户与通知执行的交互(这可以是点击通知,或通过 通知类别 与其交互),以及通知可能被删除的极少数情况。

¥Notification events include incoming notifications, interactions your users perform with notifications (this can be tapping on a notification, or interacting with it via notification categories), and rare occasions when your notifications may be dropped.

暴露了一些不同的监听器,因此我们提供了下面的图表,希望可以帮助你了解何时可以触发每个监听器:

¥A few different listeners are exposed, so we've provided a chart below which will hopefully help you understand when you can expect each one to be triggered:

用户与通知进行了交互吗?应用状态监听器被触发
false前景NotificationReceivedListener
false前景或背景BackgroundNotificationTask
false被杀none
true前景NotificationReceivedListenerNotificationResponseReceivedListener
true背景NotificationResponseReceivedListener
true被杀NotificationResponseReceivedListener

在上表中,每当 NotificationResponseReceivedListener 被触发时,同样的情况也适用于 useLastNotificationResponse 钩子。

¥In the table above, whenever NotificationResponseReceivedListener is triggered, the same would apply to the useLastNotificationResponse hook.

后台通知

¥Background notifications

Expo Go 不支持后台事件监听器。

后台通知 (iOS) 或纯数据通知 (Android) 是一种远程通知,不会显示警报、播放声音或向应用图标添加徽章。后台通知的目的是提供一种唤醒应用以在后台触发应用数据刷新的方法。

¥A background notification (iOS) or a data-only notification (Android) is a remote notification that does not display an alert, play a sound, or add a badge to your app's icon. The purpose of a background notification is to provide a way to wake up your app to trigger an app data refresh in the background.

要在 iOS 上应用处于后台时处理通知,请将 remote-notification 作为值添加到 应用配置ios.infoPlist.UIBackgroundModes 键下的数组中,并将 "content-available": 1 添加到推送通知负载中。在正常情况下,如果你的应用未运行且未被用户终止,则 "content-available" 标志应该启动你的应用。然而,这最终是由操作系统决定的,所以它可能并不总是发生。

¥To handle notifications while the app is in the background on iOS, add remote-notification as a value to the array under ios.infoPlist.UIBackgroundModes key in your app config, and add "content-available": 1 to your push notification payload. Under normal circumstances, the "content-available" flag should launch your app if it isn't running and wasn't killed by the user. However, this is ultimately decided by the OS, so it might not always happen.

在 Android 上,使用推送通知请求负载的 data 键发送纯数据通知。

¥On Android, data-only notifications are sent using the data key of the push notification request payload.

附加信息

¥Additional information

设置自定义通知声音

¥Set custom notification sounds

仅当使用 EAS 构建 时才支持自定义通知声音。

¥Custom notification sounds are only supported when using EAS Build.

要将自定义推送通知声音添加到你的应用,请将 expo-notifications 插件添加到你的 app.json 文件,然后在 sounds 键下,提供可用作自定义通知声音的声音文件的本地路径数组。这些本地路径是你项目的本地路径。

¥To add custom push notification sounds to your app, add the expo-notifications plugin to your app.json file and then under the sounds key, provide an array of local paths to sound files that can be used as custom notification sounds. These local paths are local to your project.

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "sounds": ["local/path/to/mySoundFile.wav"]
        }
      ]
    ]
  }
}

构建应用后,文件数组将可在 NotificationContentInputNotificationChannelInput 中使用。你只需提供基本文件名。这是使用上面配置的示例:

¥After building your app, the array of files will be available for use in both NotificationContentInput and NotificationChannelInput. You only need to provide the base filename. Here's an example using the config above:

await Notifications.setNotificationChannelAsync('new-emails', {
  name: 'E-mail notifications',
  sound: 'mySoundFile.wav', // Provide ONLY the base filename
});

await Notifications.scheduleNotificationAsync({
  content: {
    title: "You've got mail! 📬",
    sound: 'mySoundFile.wav', // Provide ONLY the base filename
  },
  trigger: {
    seconds: 2,
    channelId: 'new-emails',
  },
});

如果你愿意,还可以手动将通知文件添加到 Android 和 iOS 项目中:

¥You can also manually add notification files to your Android and iOS projects if you prefer:

Manually adding notification sounds on Android

在 Android 8.0+ 上,播放通知的自定义声音需要的不仅仅是在 NotificationContentInput 上设置 sound 属性。你还需要使用适当的 sound 配置 NotificationChannel,并在发送/安排通知时使用它。

¥On Androids 8.0+, playing a custom sound for a notification requires more than setting the sound property on the NotificationContentInput. You will also need to configure the NotificationChannel with the appropriate sound, and use it when sending/scheduling the notification.

为了使下面的示例正常工作,你可以将 email-sound.wav 文件放在 android/app/src/main/res/raw/ 中。

¥For the example below to work, you would place your email-sound.wav file in android/app/src/main/res/raw/.

// Prepare the notification channel
await Notifications.setNotificationChannelAsync('new-emails', {
  name: 'E-mail notifications',
  importance: Notifications.AndroidImportance.HIGH,
  sound: 'email-sound.wav', // <- for Android 8.0+, see channelId property below
});

// Eg. schedule the notification
await Notifications.scheduleNotificationAsync({
  content: {
    title: "You've got mail! 📬",
    body: 'Open the notification to read them all',
    sound: 'email-sound.wav', // <- for Android below 8.0
  },
  trigger: {
    seconds: 2,
    channelId: 'new-emails', // <- for Android 8.0+, see definition above
  },
});
Manually adding notification sounds on iOS

在 iOS 上,所需要做的就是将声音文件放入 Xcode 项目中(请参见下面的屏幕截图),然后在 NotificationContentInput 中指定声音文件,如下所示:

¥On iOS, all that's needed is to place your sound file in your Xcode project (see the screenshot below), and then specify the sound file in your NotificationContentInput, like this:

await Notifications.scheduleNotificationAsync({
  content: {
    title: "You've got mail! 📬",
    body: 'Open the notification to read them all',
    sound: 'notification.wav',
  },
  trigger: {
    // ...
  },
});

Android 推送通知负载规范

¥Android push notification payload specification

发送推送通知时,将符合以下类型的对象作为通知的 data

¥When sending a push notification, put an object conforming to the following type as data of the notification:

export interface FirebaseData {
  title?: string;
  message?: string;
  subtitle?: string;
  sound?: boolean | string;
  vibrate?: boolean | number[];
  priority?: AndroidNotificationPriority;
  badge?: number;
}

解释 iOS 权限响应

¥Interpret the iOS permissions response

在 iOS 上,发送通知的权限比 Android 上的更细化。因此,你应该依赖 NotificationPermissionsStatusios.status 字段,而不是根 status 字段。该值将是以下值之一,可在 Notifications.IosAuthorizationStatus 下访问:

¥On iOS, permissions for sending notifications are a little more granular than they are on Android. Because of this, you should rely on the NotificationPermissionsStatus's ios.status field, instead of the root status field. This value will be one of the following, accessible under Notifications.IosAuthorizationStatus:

  • NOT_DETERMINED:用户尚未选择是否允许应用安排通知

    ¥NOT_DETERMINED: The user hasn't yet made a choice about whether the app is allowed to schedule notifications

  • DENIED:该应用无权安排或接收通知

    ¥DENIED: The app isn't authorized to schedule or receive notifications

  • AUTHORIZED:该应用被授权安排或接收通知

    ¥AUTHORIZED: The app is authorized to schedule or receive notifications

  • PROVISIONAL:该应用被临时授权发布不间断的用户通知

    ¥PROVISIONAL: The application is provisionally authorized to post noninterruptive user notifications

  • EPHEMERAL:该应用被授权在有限的时间内安排或接收通知

    ¥EPHEMERAL: The app is authorized to schedule or receive notifications for a limited amount of time

管理通知类别(交互式通知)

¥Manage notification categories (interactive notifications)

通知类别允许你创建交互式推送通知,以便用户可以通过按钮或文本响应直接响应传入的通知。类别定义用户可以执行的一组操作,然后通过在 NotificationContent 中指定 categoryIdentifier 将这些操作应用于通知。

¥Notification categories allow you to create interactive push notifications, so that a user can respond directly to the incoming notification either via buttons or a text response. A category defines the set of actions a user can take, and then those actions are applied to a notification by specifying the categoryIdentifier in the NotificationContent.

在 iOS 上,通知类别还允许你进一步自定义通知。对于每个类别,你不仅可以设置用户可以执行的交互操作,还可以配置诸如当用户禁用应用的通知预览时显示的占位符文本之类的内容。

¥On iOS, notification categories also allow you to customize your notifications further. With each category, not only can you set interactive actions a user can take, but you can also configure things like the placeholder text to display when the user disables notification previews for your app.

Web 上不支持通知类别,所有相关方法都将导致 noop。

¥Notification categories are not supported on the web and all related methods will result in noop.

平台特定指南

¥Platform specific guides

处理通知渠道

¥Handling notification channels

Android 8+

从 Android 8.0(API 级别 26)开始,所有通知都必须分配给一个通道。对于每个通道,你可以设置应用于该通道中所有通知的视觉和听觉行为。然后,用户可以更改这些设置并决定应用中的哪些通知渠道应该是侵入性的或完全可见的,如 Android 开发者文档 所述。

¥Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel. For each channel, you can set the visual and auditory behavior that is applied to all notifications in that channel. Then, users can change these settings and decide which notification channels from your app should be intrusive or visible at all, as Android developer docs states.

如果你不指定通知渠道,expo-notifications 将为你创建一个后备渠道,名为 Miscellaneous。我们鼓励你始终确保为应用设置具有信息名称的适当渠道,并始终向这些渠道发送通知。

¥If you do not specify a notification channel, expo-notifications will create a fallback channel for you, named Miscellaneous. We encourage you to always ensure appropriate channels with informative names are set up for the application and to always send notifications to these channels.

对于不支持此功能的平台(Android 8.0 (26) 以下版本、iOS 和 Web),调用这些方法是无操作的。

¥Calling these methods is a no-op for platforms that do not support this feature (Android below version 8.0 (26), iOS and web).

自定义通知图标和颜色

¥Custom notification icon and colors

Android

如果你使用 Expo 预建 或使用 直接 expo-notifications 配置插件,则可以在项目的 app.json 中配置 notification.iconnotification.color 键。这些是构建时设置,因此你需要使用 eas build -p androidnpx expo run:android 重新编译原生 Android 应用才能看到更改。

¥You can configure the notification.icon and notification.color keys in the project's app.json if you are using Expo Prebuild or by using the expo-notifications config plugin directly. These are build-time settings, so you'll need to recompile your native Android app with eas build -p android or npx expo run:android to see the changes.

对于你的通知图标,请确保遵循 Google 的设计指南(图标必须是全白透明背景),否则可能无法按预期显示。

¥For your notification icon, make sure you follow Google's design guidelines (the icon must be all white with a transparent background) or else it may not be displayed as intended.

你还可以直接在 NotificationContentInput 中的 color 属性下设置每个通知的自定义通知颜色。

¥You can also set a custom notification color per-notification directly in your NotificationContentInput under the color attribute.

API

import * as Notifications from 'expo-notifications';

Fetch tokens for push notifications

addPushTokenListener(listener)

NameTypeDescription
listenerPushTokenListener

A function accepting a push token as an argument, it will be called whenever the push token changes.


In rare situations, a push token may be changed by the push notification service while the app is running. When a token is rolled, the old one becomes invalid and sending notifications to it will fail. A push token listener will let you handle this situation gracefully by registering the new token with your backend right away.

Example

import React from 'react';
import * as Notifications from 'expo-notifications';

import { registerDevicePushTokenAsync } from '../api';

export default function App() {
  React.useEffect(() => {
    const subscription = Notifications.addPushTokenListener(registerDevicePushTokenAsync);
    return () => subscription.remove();
  }, []);

  return (
    // Your app content
  );
}

Returns

  • Subscription

A Subscription object represents the subscription of the provided listener.

getDevicePushTokenAsync()

Returns a native FCM, APNs token or a PushSubscription data that can be used with another push notification service.

Returns

  • Promise<DevicePushToken>

getExpoPushTokenAsync(options)

NameTypeDescription
options
(optional)
ExpoPushTokenOptions

Object allowing you to pass in push notification configuration.

Default: {}

Returns an Expo token that can be used to send a push notification to the device using Expo's push notifications service.

This method makes requests to the Expo's servers. It can get rejected in cases where the request itself fails (for example, due to the device being offline, experiencing a network timeout, or other HTTPS request failures). To provide offline support to your users, you should try/catch this method and implement retry logic to attempt to get the push token later, once the device is back online.

For Expo's backend to be able to send notifications to your app, you will need to provide it with push notification keys. For more information, see credentials in the push notifications setup.

Example

import * as Notifications from 'expo-notifications';

export async function registerForPushNotificationsAsync(userId: string) {
  const expoPushToken = await Notifications.getExpoPushTokenAsync({
   projectId: 'your-project-id',
  });

  await fetch('https://example.com/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      userId,
      expoPushToken,
    }),
  });
}

Returns

  • Promise<ExpoPushToken>

Returns a Promise that resolves to an object representing acquired push token.

removePushTokenSubscription(subscription)

NameTypeDescription
subscriptionSubscription

A subscription returned by addPushTokenListener method.


Removes a push token subscription returned by an addPushTokenListener call.

Returns

  • void

Listen to notification events

addNotificationReceivedListener(listener)

NameTypeDescription
listener(event: Notification) => void

A function accepting a notification (Notification) as an argument.


Listeners registered by this method will be called whenever a notification is received while the app is running.

Example

import React from 'react';
import * as Notifications from 'expo-notifications';

export default function App() {
  React.useEffect(() => {
    const subscription = Notifications.addNotificationReceivedListener(notification => {
      console.log(notification);
    });
    return () => subscription.remove();
  }, []);

  return (
    // Your app content
  );
}

Returns

  • Subscription

A Subscription object represents the subscription of the provided listener.

addNotificationResponseReceivedListener(listener)

NameTypeDescription
listener(event: NotificationResponse) => void

A function accepting notification response (NotificationResponse) as an argument.


Listeners registered by this method will be called whenever a user interacts with a notification (for example, taps on it).

Example

import React from 'react';
import { Linking } from 'react-native';
import * as Notifications from 'expo-notifications';

export default function Container() {
  React.useEffect(() => {
    const subscription = Notifications.addNotificationResponseReceivedListener(response => {
      const url = response.notification.request.content.data.url;
      Linking.openURL(url);
    });
    return () => subscription.remove();
  }, []);

  return (
    // Your app content
  );
}

Returns

  • Subscription

A Subscription object represents the subscription of the provided listener.

addNotificationsDroppedListener(listener)

NameTypeDescription
listener() => void

A callback function.


Listeners registered by this method will be called whenever some notifications have been dropped by the server. Applicable only to Firebase Cloud Messaging which we use as a notifications service on Android. It corresponds to onDeletedMessages() callback. More information can be found in Firebase docs.

Returns

  • Subscription

A Subscription object represents the subscription of the provided listener.

getLastNotificationResponseAsync()

Returns

  • Promise<NotificationResponse | null>

removeNotificationSubscription(subscription)

NameTypeDescription
subscriptionSubscription

A subscription returned by addNotificationListener method.


Removes a notification subscription returned by an addNotificationListener call.

Returns

  • void

useLastNotificationResponse()

A React hook always returns the notification response that was received most recently (a notification response designates an interaction with a notification, such as tapping on it).

If you don't want to use a hook, you can use Notifications.getLastNotificationResponseAsync() instead.

Example

Responding to a notification tap by opening a URL that could be put into the notification's data (opening the URL is your responsibility and is not a part of the expo-notifications API):

import * as Notifications from 'expo-notifications';
import { Linking } from 'react-native';

export default function App() {
  const lastNotificationResponse = Notifications.useLastNotificationResponse();
  React.useEffect(() => {
    if (
      lastNotificationResponse &&
      lastNotificationResponse.notification.request.content.data.url &&
      lastNotificationResponse.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER
    ) {
      Linking.openURL(lastNotificationResponse.notification.request.content.data.url);
    }
  }, [lastNotificationResponse]);
  return (
    // Your app content
  );
}

Returns

  • undefined | null | NotificationResponse

The hook may return one of these three types/values:

  • undefined - until we're sure of what to return,
  • null - if no notification response has been received yet,
  • a NotificationResponse object - if a notification response was received.

Handle incoming notifications when the app is in the foreground

setNotificationHandler(handler)

NameTypeDescription
handlernull | NotificationHandler

A single parameter which should be either null (if you want to clear the handler) or a NotificationHandler object.


When a notification is received while the app is running, using this function you can set a callback that will decide whether the notification should be shown to the user or not.

When a notification is received, handleNotification is called with the incoming notification as an argument. The function should respond with a behavior object within 3 seconds, otherwise, the notification will be discarded. If the notification is handled successfully, handleSuccess is called with the identifier of the notification, otherwise (or on timeout) handleError will be called.

The default behavior when the handler is not set or does not respond in time is not to show the notification.

Example

import * as Notifications from 'expo-notifications';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

Returns

  • void

Handle incoming notifications when the app is not in the foreground

registerTaskAsync(taskName)

NameTypeDescription
taskNamestring

The string you passed to TaskManager.defineTask as the taskName parameter.


When a notification is received while the app is backgrounded, using this function you can set a callback that will be run in response to that notification. Under the hood, this function is run using expo-task-manager. You must define the task first, with TaskManager.defineTask. Make sure you define it in the global scope.

The callback function you define with TaskManager.defineTask will receive an object with the following fields:

  • data: The remote payload delivered by either FCM (Android) or APNs (iOS). See PushNotificationTrigger for details.
  • error: The error (if any) that occurred during execution of the task.
  • executionInfo: JSON object of additional info related to the task, including the taskName.

Example

import * as TaskManager from 'expo-task-manager';
import * as Notifications from 'expo-notifications';

const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';

TaskManager.defineTask(BACKGROUND_NOTIFICATION_TASK, ({ data, error, executionInfo }) => {
  console.log('Received a notification in the background!');
  // Do something with the notification data
});

Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);

Returns


unregisterTaskAsync(taskName)

NameTypeDescription
taskNamestring

The string you passed to registerTaskAsync as the taskName parameter.


Used to unregister tasks registered with registerTaskAsync method.

Returns

  • Promise<null>

Fetch information about notifications-related permissions

getPermissionsAsync()

Calling this function checks current permissions settings related to notifications. It lets you verify whether the app is currently allowed to display alerts, play sounds, etc. There is no user-facing effect of calling this.

Example

import * as Notifications from 'expo-notifications';

export async function allowsNotificationsAsync() {
  const settings = await Notifications.getPermissionsAsync();
  return (
    settings.granted || settings.ios?.status === Notifications.IosAuthorizationStatus.PROVISIONAL
  );
}

Returns

  • Promise<NotificationPermissionsStatus>

It returns a Promise resolving to an object represents permission settings (NotificationPermissionsStatus). On iOS, make sure you properly interpret the permissions response.

requestPermissionsAsync(permissions)

NameTypeDescription
permissions
(optional)
NotificationPermissionsRequest

An object representing configuration for the request scope.


Prompts the user for notification permissions according to request. Request defaults to asking the user to allow displaying alerts, setting badge count and playing sounds.

Example

import * as Notifications from 'expo-notifications';

export function requestPermissionsAsync() {
  return await Notifications.requestPermissionsAsync({
    ios: {
      allowAlert: true,
      allowBadge: true,
      allowSound: true,
      allowAnnouncements: true,
    },
  });
}

Returns

  • Promise<NotificationPermissionsStatus>

It returns a Promise resolving to an object represents permission settings (NotificationPermissionsStatus). On iOS, make sure you properly interpret the permissions response.

Manage application badge icon

getBadgeCountAsync()

Fetches the number currently set as the badge of the app icon on device's home screen. A 0 value means that the badge is not displayed.

Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will always resolve to 0.

Returns

  • Promise<number>

Returns a Promise resolving to a number that represents the current badge of the app icon.

setBadgeCountAsync(badgeCount, options)

NameTypeDescription
badgeCountnumber

The count which should appear on the badge. A value of 0 will clear the badge.

options
(optional)
SetBadgeCountOptions

An object of options configuring behavior applied in Web environment.


Sets the badge of the app's icon to the specified number. Setting it to 0 clears the badge. On iOS, this method requires that you have requested the user's permission for allowBadge via requestPermissionsAsync, otherwise it will automatically return false.

Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will resolve to false.

Returns

  • Promise<boolean>

It returns a Promise resolving to a boolean representing whether the setting of the badge succeeded.

Schedule notifications

cancelAllScheduledNotificationsAsync()

Cancels all scheduled notifications.

Returns

  • Promise<void>

A Promise that resolves once all the scheduled notifications are successfully canceled, or if there are no scheduled notifications.

cancelScheduledNotificationAsync(identifier)

NameTypeDescription
identifierstring

The notification identifier with which scheduleNotificationAsync method resolved when the notification has been scheduled.


Cancels a single scheduled notification. The scheduled notification of given ID will not trigger.

Example

import * as Notifications from 'expo-notifications';

async function scheduleAndCancel() {
  const identifier = await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Hey!',
    },
    trigger: { seconds: 60, repeats: true },
  });
  await Notifications.cancelScheduledNotificationAsync(identifier);
}

Returns

  • Promise<void>

A Promise resolves once the scheduled notification is successfully canceled or if there is no scheduled notification for a given identifier.

getAllScheduledNotificationsAsync()

Fetches information about all scheduled notifications.

Returns

  • Promise<NotificationRequest[]>

Returns a Promise resolving to an array of objects conforming to the Notification interface.

getNextTriggerDateAsync(trigger)

NameTypeDescription
triggerSchedulableNotificationTriggerInput

The schedulable notification trigger you would like to check next trigger date for (of type SchedulableNotificationTriggerInput).


Allows you to check what will be the next trigger date for given notification trigger input.

Example

import * as Notifications from 'expo-notifications';

async function logNextTriggerDate() {
  try {
    const nextTriggerDate = await Notifications.getNextTriggerDateAsync({
      hour: 9,
      minute: 0,
    });
    console.log(nextTriggerDate === null ? 'No next trigger date' : new Date(nextTriggerDate));
  } catch (e) {
    console.warn(`Couldn't have calculated next trigger date: ${e}`);
  }
}

Returns

  • Promise<number | null>

If the return value is null, the notification won't be triggered. Otherwise, the return value is the Unix timestamp in milliseconds at which the notification will be triggered.

Deprecated. This method has been deprecated in favor of using an explicit NotificationHandler and the scheduleNotificationAsync method. More information can be found in our FYI document.

presentNotificationAsync(content, identifier)

NameTypeDescription
contentNotificationContentInput

An object representing the notification content.

identifier
(optional)
string-

Schedules a notification for immediate trigger.

Returns

  • Promise<string>

It returns a Promise resolving with the notification's identifier once the notification is successfully scheduled for immediate display.

scheduleNotificationAsync(request)

NameTypeDescription
requestNotificationRequestInput

An object describing the notification to be triggered.


Schedules a notification to be triggered in the future.

Note: Please note that this does not mean that the notification will be presented when it is triggered. For the notification to be presented you have to set a notification handler with setNotificationHandler that will return an appropriate notification behavior. For more information see the example below.

Example

Schedule the notification that will trigger once, in one minute from now

import * as Notifications from 'expo-notifications';

Notifications.scheduleNotificationAsync({
  content: {
    title: "Time's up!",
    body: 'Change sides!',
  },
  trigger: {
    seconds: 60,
  },
});

Schedule the notification that will trigger repeatedly, every 20 minutes

import * as Notifications from 'expo-notifications';

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Remember to drink water!',
  },
  trigger: {
    seconds: 60 * 20,
    repeats: true,
  },
});

Schedule the notification that will trigger once, at the beginning of next hour

import * as Notifications from 'expo-notifications';

const trigger = new Date(Date.now() + 60 * 60 * 1000);
trigger.setMinutes(0);
trigger.setSeconds(0);

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Happy new hour!',
  },
  trigger,
});

Returns

  • Promise<string>

Returns a Promise resolving to a string which is a notification identifier you can later use to cancel the notification or to identify an incoming notification.

Dismiss notifications

dismissAllNotificationsAsync()

Removes all application's notifications displayed in the notification tray (Notification Center).

Returns

  • Promise<void>

A Promise which resolves once the request to dismiss the notifications is successfully dispatched to the notifications manager.

dismissNotificationAsync(notificationIdentifier)

NameTypeDescription
notificationIdentifierstring

The notification identifier, obtained either via setNotificationHandler method or in the listener added with addNotificationReceivedListener.


Removes notification displayed in the notification tray (Notification Center).

Returns

  • Promise<void>

A Promise which resolves once the request to dismiss the notification is successfully dispatched to the notifications manager.

getPresentedNotificationsAsync()

Fetches information about all notifications present in the notification tray (Notification Center).

This method is not supported on Android below 6.0 (API level 23) – on these devices it will resolve to an empty array.

Returns

  • Promise<Notification[]>

A Promise which resolves with a list of notifications (Notification) currently present in the notification tray (Notification Center).

Manage notification channels (Android-specific)

Only for: 
Android

deleteNotificationChannelAsync(channelId)

NameTypeDescription
channelIdstring

The channel identifier.


Removes the notification channel.

Returns

  • Promise<void>

A Promise which resolving once the channel is removed (or if there was no channel for given identifier).

Only for: 
Android

deleteNotificationChannelGroupAsync(groupId)

NameTypeDescription
groupIdstring

The channel group identifier.


Removes the notification channel group and all notification channels that belong to it.

Returns

  • Promise<void>

A Promise which resolves once the channel group is removed (or if there was no channel group for given identifier).

Only for: 
Android

getNotificationChannelAsync(channelId)

NameTypeDescription
channelIdstring

The channel's identifier.


Fetches information about a single notification channel.

Returns

  • Promise<NotificationChannel | null>

A Promise which resolves to the channel object (of type NotificationChannel) or to null if there was no channel found for this identifier. On platforms that do not support notification channels, it will always resolve to null.

Only for: 
Android

getNotificationChannelGroupAsync(groupId)

NameTypeDescription
groupIdstring

The channel group's identifier.


Fetches information about a single notification channel group.

Returns

  • Promise<NotificationChannelGroup | null>

A Promise which resolves to the channel group object (of type NotificationChannelGroup) or to null if there was no channel group found for this identifier. On platforms that do not support notification channels, it will always resolve to null.

Only for: 
Android

getNotificationChannelGroupsAsync()

Fetches information about all known notification channel groups.

Returns

  • Promise<NotificationChannelGroup[]>

A Promise which resoles to an array of channel groups. On platforms that do not support notification channel groups, it will always resolve to an empty array.

Only for: 
Android

getNotificationChannelsAsync()

Fetches information about all known notification channels.

Returns

  • Promise<NotificationChannel[]>

A Promise which resolves to an array of channels. On platforms that do not support notification channels, it will always resolve to an empty array.

Only for: 
Android

setNotificationChannelAsync(channelId, channel)

NameTypeDescription
channelIdstring

The channel identifier.

channelNotificationChannelInput

Object representing the channel's configuration.


Assigns the channel configuration to a channel of a specified name (creating it if need be). This method lets you assign given notification channel to a notification channel group.

Note: For some settings to be applied on all Android versions, it may be necessary to duplicate the configuration across both a single notification and its respective notification channel.

For example, for a notification to play a custom sound on Android versions below 8.0, the custom notification sound has to be set on the notification (through the NotificationContentInput), and for the custom sound to play on Android versions above 8.0, the relevant notification channel must have the custom sound configured (through the NotificationChannelInput). For more information, see Set custom notification sounds on Android.

Returns

  • Promise<NotificationChannel | null>

A Promise which resolving to the object (of type NotificationChannel) describing the modified channel or to null if the platform does not support notification channels.

Only for: 
Android

setNotificationChannelGroupAsync(groupId, group)

NameTypeDescription
groupIdstring

The channel group's identifier.

groupNotificationChannelGroupInput

Object representing the channel group configuration.


Assigns the channel group configuration to a channel group of a specified name (creating it if need be).

Returns

  • Promise<NotificationChannelGroup | null>

A Promise resolving to the object (of type NotificationChannelGroup) describing the modified channel group or to null if the platform does not support notification channels.

Manage notification categories (interactive notifications)

Only for: 
Android
iOS

deleteNotificationCategoryAsync(identifier)

NameTypeDescription
identifierstring

Identifier initially provided to setNotificationCategoryAsync when creating the category.


Deletes the category associated with the provided identifier.

Returns

  • Promise<boolean>

A Promise which resolves to true if the category was successfully deleted, or false if it was not. An example of when this method would return false is if you try to delete a category that doesn't exist.

Only for: 
Android
iOS

getNotificationCategoriesAsync()

Fetches information about all known notification categories.

Returns

  • Promise<NotificationCategory[]>

A Promise which resolves to an array of NotificationCategorys. On platforms that do not support notification channels, it will always resolve to an empty array.

Only for: 
Android
iOS
Web

setNotificationCategoryAsync(identifier, actions, options)

NameTypeDescription
identifierstring

A string to associate as the ID of this category. You will pass this string in as the categoryIdentifier in your NotificationContent to associate a notification with this category.

Don't use the characters : or - in your category identifier. If you do, categories might not work as expected.

actionsNotificationAction[]

An array of NotificationActions, which describe the actions associated with this category.

options
(optional)
NotificationCategoryOptions

An optional object of additional configuration options for your category.


Sets the new notification category.

Returns

  • Promise<NotificationCategory>

A Promise which resolves to the category you just have created, or null on web

Constants

Notifications.DEFAULT_ACTION_IDENTIFIER

Type: 'expo.modules.notifications.actions.DEFAULT'

Methods

Notifications.setAutoServerRegistrationEnabledAsync(enabled)

NameTypeDescription
enabledboolean-

Sets the registration information so that the device push token gets pushed to the given registration endpoint

Returns

  • Promise<void>

Notifications.unregisterForNotificationsAsync()

Returns

  • Promise<void>

Interfaces

AudioAttributes

AudioAttributes Properties

NameTypeDescription
contentTypeAndroidAudioContentType-
flags{ enforceAudibility: boolean, requestHardwareAudioVideoSynchronization: boolean }-
usageAndroidAudioUsage-

Only for: 
iOS

BeaconRegion

Extends: Region

A region used to detect the presence of iBeacon devices. Based on Core Location CLBeaconRegion class.

BeaconRegion Properties

NameTypeDescription
beaconIdentityConstraint
(optional)
{ major: null | number, minor: null | number, uuid: string }

The beacon identity constraint that defines the beacon region.

majornull | number

The major value from the beacon identity constraint that defines the beacon region.

minornull | number

The minor value from the beacon identity constraint that defines the beacon region.

notifyEntryStateOnDisplayboolean

A Boolean value that indicates whether Core Location sends beacon notifications when the device’s display is on.

type'beacon'-
uuid
(optional)
string

The UUID value from the beacon identity constraint that defines the beacon region.


Only for: 
iOS

CalendarNotificationTrigger

A trigger related to a UNCalendarNotificationTrigger.

CalendarNotificationTrigger Properties

NameTypeDescription
dateComponents{ calendar: string, day: number, era: number, hour: number, isLeapMonth: boolean, minute: number, month: number, nanosecond: number, quarter: number, second: number, timeZone: string, weekOfMonth: number, weekOfYear: number, weekday: number, weekdayOrdinal: number, year: number, yearForWeekOfYear: number }-
repeatsboolean-
type'calendar'-

Only for: 
iOS

CircularRegion

Extends: Region

A circular geographic region, specified as a center point and radius. Based on Core Location CLCircularRegion class.

CircularRegion Properties

NameTypeDescription
center{ latitude: number, longitude: number }

The center point of the geographic area.

radiusnumber

The radius (measured in meters) that defines the geographic area’s outer boundary.

type'circular'-

Only for: 
Android

DailyNotificationTrigger

A trigger related to a daily notification.

The same functionality will be achieved on iOS with a CalendarNotificationTrigger.

DailyNotificationTrigger Properties

NameTypeDescription
hournumber-
minutenumber-
type'daily'-

DailyTriggerInput

A trigger that will cause the notification to be delivered once per day.

DailyTriggerInput Properties

NameTypeDescription
channelId
(optional)
string-
hournumber-
minutenumber-
repeatstrue-

ExpoPushToken

Borrowing structure from DevicePushToken a little. You can use the data value to send notifications via Expo Notifications service.

ExpoPushToken Properties

NameTypeDescription
datastring

The acquired push token.

type'expo'

Always set to "expo".


ExpoPushTokenOptions

ExpoPushTokenOptions Properties

NameTypeDescription
applicationId
(optional)
string

The ID of the application to which the token should be attributed. Defaults to Application.applicationId exposed by expo-application.

baseUrl
(optional)
string

Endpoint URL override.

development
(optional)
booleanOnly for: 
iOS

Makes sense only on iOS, where there are two push notification services: "sandbox" and "production". This defines whether the push token is supposed to be used with the sandbox platform notification service. Defaults to Application.getIosPushNotificationServiceEnvironmentAsync() exposed by expo-application or false. Most probably you won't need to customize that. You may want to customize that if you don't want to install expo-application and still use the sandbox APNs.

deviceId
(optional)
string-
devicePushToken
(optional)
DevicePushToken

The device push token with which to register at the backend. Defaults to a token fetched with getDevicePushTokenAsync().

projectId
(optional)
string

The ID of the project to which the token should be attributed. Defaults to Constants.expoConfig.extra.eas.projectId exposed by expo-constants.

When using EAS Build, this value is automatically set. However, it is recommended to set it manually. Once you have EAS Build configured, you can find the value in app.json under extra.eas.projectId. You can copy and paste it into your code. If you are not using EAS Build, it will fallback to Constants.expoConfig?.extra?.eas?.projectId.

type
(optional)
string

Request body override.

url
(optional)
string

Request URL override.


FirebaseRemoteMessage

A Firebase RemoteMessage that caused the notification to be delivered to the app.

FirebaseRemoteMessage Properties

NameTypeDescription
collapseKeynull | string-
dataRecord<string, string>-
fromnull | string-
messageIdnull | string-
messageTypenull | string-
notificationnull | FirebaseRemoteMessageNotification-
originalPrioritynumber-
prioritynumber-
sentTimenumber-
tonull | string-
ttlnumber-

FirebaseRemoteMessageNotification

FirebaseRemoteMessageNotification Properties

NameTypeDescription
bodynull | string-
bodyLocalizationArgsnull | string[]-
bodyLocalizationKeynull | string-
channelIdnull | string-
clickActionnull | string-
colornull | string-
eventTimenull | number-
iconnull | string-
imageUrlnull | string-
lightSettingsnull | number[]-
linknull | string-
localOnlyboolean-
notificationCountnull | number-
notificationPrioritynull | number-
soundnull | string-
stickyboolean-
tagnull | string-
tickernull | string-
titlenull | string-
titleLocalizationArgsnull | string[]-
titleLocalizationKeynull | string-
usesDefaultLightSettingsboolean-
usesDefaultSoundboolean-
usesDefaultVibrateSettingsboolean-
vibrateTimingsnull | number[]-
visibilitynull | number-

IosNotificationPermissionsRequest

Available configuration for permission request on iOS platform. See Apple documentation for UNAuthorizationOptions to learn more.

IosNotificationPermissionsRequest Properties

NameTypeDescription
allowAlert
(optional)
boolean

The ability to display alerts.

allowAnnouncements
(optional)
boolean
Deprecated

The ability for Siri to automatically read out messages over AirPods.

allowBadge
(optional)
boolean

The ability to update the app’s badge.

allowCriticalAlerts
(optional)
boolean

The ability to play sounds for critical alerts.

allowDisplayInCarPlay
(optional)
boolean

The ability to display notifications in a CarPlay environment.

allowProvisional
(optional)
boolean

The ability to post noninterrupting notifications provisionally to the Notification Center.

allowSound
(optional)
boolean

The ability to play sounds.

provideAppNotificationSettings
(optional)
boolean

An option indicating the system should display a button for in-app notification settings.


Only for: 
iOS

LocationNotificationTrigger

A trigger related to a UNLocationNotificationTrigger.

LocationNotificationTrigger Properties

NameTypeDescription
regionCircularRegion | BeaconRegion-
repeatsboolean-
type'location'-

NativeDevicePushToken

NativeDevicePushToken Properties

NameTypeDescription
datastring-
type'ios' | 'android'-

Notification

An object represents a single notification that has been triggered by some request (NotificationRequest) at some point in time.

Notification Properties

NameTypeDescription
datenumber-
requestNotificationRequest-

NotificationAction

NotificationAction Properties

NameTypeDescription
buttonTitlestring

The title of the button triggering this action.

identifierstring

A unique string that identifies this action. If a user takes this action (for example, selects this button in the system's Notification UI), your app will receive this actionIdentifier via the NotificationResponseReceivedListener.

options
(optional)
{ isAuthenticationRequired: boolean, isDestructive: boolean, opensAppToForeground: boolean }

Object representing the additional configuration options.

textInput
(optional)
{ placeholder: string, submitButtonTitle: string }

Object which, if provided, will result in a button that prompts the user for a text response.


NotificationBehavior

An object represents behavior that should be applied to the incoming notification.

On Android, setting shouldPlaySound: false will result in the drop-down notification alert not showing, no matter what the priority is. This setting will also override any channel-specific sounds you may have configured.

NotificationBehavior Properties

NameTypeDescription
priority
(optional)
AndroidNotificationPriority-
shouldPlaySoundboolean-
shouldSetBadgeboolean-
shouldShowAlertboolean-

NotificationCategory

NotificationCategory Properties

NameTypeDescription
actionsNotificationAction[]-
identifierstring-
options
(optional)
NotificationCategoryOptions-

Only for: 
Android

NotificationChannel

An object represents a notification channel.

NotificationChannel Properties

NameTypeDescription
audioAttributesAudioAttributes-
bypassDndboolean-
descriptionnull | string-
enableLightsboolean-
enableVibrateboolean-
groupId
(optional)
null | string-
idstring-
importanceAndroidImportance-
lightColorstring-
lockscreenVisibilityAndroidNotificationVisibility-
namenull | string-
showBadgeboolean-
soundnull | 'default' | 'custom'-
vibrationPatternnull | number[]-

Only for: 
Android

NotificationChannelGroup

An object represents a notification channel group.

NotificationChannelGroup Properties

NameTypeDescription
channelsNotificationChannel[]-
description
(optional)
null | string-
idstring-
isBlocked
(optional)
boolean-
namenull | string-

Only for: 
Android

NotificationChannelGroupInput

An object represents a notification channel group to be set.

NotificationChannelGroupInput Properties

NameTypeDescription
description
(optional)
null | string-
namenull | string-

NotificationChannelGroupManager

Extends: ProxyNativeModule

NotificationChannelGroupManager Properties

NameTypeDescription
deleteNotificationChannelGroupAsync
(optional)
(groupId: string) => Promise<void>-
getNotificationChannelGroupAsync
(optional)
(groupId: string) => Promise<null | NotificationChannelGroup>-
getNotificationChannelGroupsAsync
(optional)
() => Promise<NotificationChannelGroup[]>-
setNotificationChannelGroupAsync
(optional)
(groupId: string, group: NotificationChannelGroupInput) => Promise<null | NotificationChannelGroup>-

NotificationChannelManager

Extends: ProxyNativeModule

NotificationChannelManager Properties

NameTypeDescription
deleteNotificationChannelAsync
(optional)
(channelId: string) => Promise<void>-
getNotificationChannelAsync
(optional)
(channelId: string) => Promise<null | NotificationChannel>-
getNotificationChannelsAsync
(optional)
() => Promise<null | NotificationChannel[]>-
setNotificationChannelAsync
(optional)
(channelId: string, channelConfiguration: NotificationChannelInput) => Promise<null | NotificationChannel>-

NotificationHandler

NotificationHandler Properties

NameTypeDescription
handleError
(optional)
(notificationId: string, error: NotificationHandlingError) => void

A function called whenever handling of an incoming notification fails.

handleNotification(notification: Notification) => Promise<NotificationBehavior>

A function accepting an incoming notification returning a Promise resolving to a behavior (NotificationBehavior) applicable to the notification

handleSuccess
(optional)
(notificationId: string) => void

A function called whenever an incoming notification is handled successfully.


NotificationPermissionsRequest

An interface representing the permissions request scope configuration. Each option corresponds to a different native platform authorization option.

NotificationPermissionsRequest Properties

NameTypeDescription
android
(optional)
object

On Android, all available permissions are granted by default, and if a user declines any permission, an app cannot prompt the user to change.

ios
(optional)
IosNotificationPermissionsRequest

Available configuration for permission request on iOS platform.


NotificationPermissionsStatus

Extends: PermissionResponse

An object obtained by permissions get and request functions.

NotificationPermissionsStatus Properties

NameTypeDescription
android
(optional)
{ importance: number, interruptionFilter: number }-
ios
(optional)
{ alertStyle: IosAlertStyle, allowsAlert: null | boolean, allowsAnnouncements: null | boolean, allowsBadge: null | boolean, allowsCriticalAlerts: null | boolean, allowsDisplayInCarPlay: null | boolean, allowsDisplayInNotificationCenter: null | boolean, allowsDisplayOnLockScreen: null | boolean, allowsPreviews: IosAllowsPreviews, allowsSound: null | boolean, providesAppNotificationSettings: boolean, status: IosAuthorizationStatus }-

NotificationRequest

An object represents a request to present a notification. It has content — how it's being represented, and a trigger — what triggers the notification. Many notifications (Notification) may be triggered with the same request (for example, a repeating notification).

NotificationRequest Properties

NameTypeDescription
contentNotificationContent-
identifierstring-
triggerNotificationTrigger-

NotificationRequestInput

An object represents a notification request you can pass into scheduleNotificationAsync.

NotificationRequestInput Properties

NameTypeDescription
contentNotificationContentInput-
identifier
(optional)
string-
triggerNotificationTriggerInput-

NotificationResponse

An object represents user's interaction with the notification.

Note: If the user taps on a notification actionIdentifier will be equal to Notifications.DEFAULT_ACTION_IDENTIFIER.

NotificationResponse Properties

NameTypeDescription
actionIdentifierstring-
notificationNotification-
userText
(optional)
string-

PermissionResponse

An object obtained by permissions get and request functions.

PermissionResponse Properties

NameTypeDescription
canAskAgainboolean

Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.


Only for: 
iOS

Region

The region used to determine when the system sends the notification.

Region Properties

NameTypeDescription
identifierstring

The identifier for the region object.

notifyOnEntryboolean

A Boolean indicating that notifications are generated upon entry into the region.

notifyOnExitboolean

A Boolean indicating that notifications are generated upon exit from the region.

typestring-

TimeIntervalNotificationTrigger

A trigger related to an elapsed time interval. May be repeating (see repeats field).

TimeIntervalNotificationTrigger Properties

NameTypeDescription
repeatsboolean-
secondsnumber-
type'timeInterval'-

TimeIntervalTriggerInput

A trigger that will cause the notification to be delivered once or many times (depends on the repeats field) after seconds time elapse.

On iOS, when repeats is true, the time interval must be 60 seconds or greater. Otherwise, the notification won't be triggered.

TimeIntervalTriggerInput Properties

NameTypeDescription
channelId
(optional)
string-
repeats
(optional)
boolean-
secondsnumber-

UnknownNotificationTrigger

Represents a notification trigger that is unknown to expo-notifications and that it didn't know how to serialize for JS.

UnknownNotificationTrigger Properties

NameTypeDescription
type'unknown'-

WebDevicePushToken

WebDevicePushToken Properties

NameTypeDescription
data{ endpoint: string, keys: WebDevicePushTokenKeys }-
type'web'-

Only for: 
Android

WeeklyNotificationTrigger

A trigger related to a weekly notification.

The same functionality will be achieved on iOS with a CalendarNotificationTrigger.

WeeklyNotificationTrigger Properties

NameTypeDescription
hournumber-
minutenumber-
type'weekly'-
weekdaynumber-

WeeklyTriggerInput

A trigger that will cause the notification to be delivered once every week.

Note: Weekdays are specified with a number from 1 through 7, with 1 indicating Sunday.

WeeklyTriggerInput Properties

NameTypeDescription
channelId
(optional)
string-
hournumber-
minutenumber-
repeatstrue-
weekdaynumber-

Only for: 
Android

YearlyNotificationTrigger

A trigger related to a yearly notification.

The same functionality will be achieved on iOS with a CalendarNotificationTrigger.

YearlyNotificationTrigger Properties

NameTypeDescription
daynumber-
hournumber-
minutenumber-
monthnumber-
type'yearly'-

YearlyTriggerInput

A trigger that will cause the notification to be delivered once every year.

Note: all properties are specified in JavaScript Date's ranges.

YearlyTriggerInput Properties

NameTypeDescription
channelId
(optional)
string-
daynumber-
hournumber-
minutenumber-
monthnumber-
repeatstrue-

Types

AudioAttributesInput

Type: Partial<AudioAttributes>

Only for: 
iOS

CalendarTriggerInput

A trigger that will cause the notification to be delivered once or many times when the date components match the specified values. Corresponds to native UNCalendarNotificationTrigger.

CalendarTriggerInputValue extended by:


NameTypeDescription
channelId
(optional)
string-
repeats
(optional)
boolean-

CalendarTriggerInputValue

NameTypeDescription
day
(optional)
number-
hour
(optional)
number-
minute
(optional)
number-
month
(optional)
number-
second
(optional)
number-
timezone
(optional)
string-
weekOfMonth
(optional)
number-
weekOfYear
(optional)
number-
weekday
(optional)
number-
weekdayOrdinal
(optional)
number-
year
(optional)
number-

ChannelAwareTriggerInput

A trigger that will cause the notification to be delivered immediately.

NameTypeDescription
channelIdstring-

DateTriggerInput

A trigger that will cause the notification to be delivered once at the specified Date. If you pass in a number it will be interpreted as a Unix timestamp.

Date or number or object shaped as below:


NameTypeDescription
channelId
(optional)
string-
dateDate | number-

DevicePushToken

Literal Type: multiple types

In simple terms, an object of type: Platform.OS and data: any. The data type depends on the environment - on a native device it will be a string, which you can then use to send notifications via Firebase Cloud Messaging (Android) or APNs (iOS); on web it will be a registration object (VAPID).

Acceptable values are: ExplicitlySupportedDevicePushToken | ImplicitlySupportedDevicePushToken

ExplicitlySupportedDevicePushToken

Literal Type: multiple types

Acceptable values are: NativeDevicePushToken | WebDevicePushToken

ImplicitlySupportedDevicePushToken

NameTypeDescription
dataany

Either the push token as a string (when for native platforms), or an object conforming to the type below (for web):

{
  endpoint: string;
  keys: {
    p256dh: string;
    auth: string;
  }
}
typeExclude<Platform.OS, ExplicitlySupportedDevicePushToken['type']>

Either android, ios or web.

NativeNotificationPermissionsRequest

Literal Type: multiple types

Acceptable values are: IosNotificationPermissionsRequest | object

Only for: 
iOS

NotificationCategoryOptions

NameTypeDescription
allowAnnouncement
(optional)
boolean

A boolean indicating whether to allow notifications to be automatically read by Siri when the user is using AirPods.

Default: false
allowInCarPlay
(optional)
boolean

A boolean indicating whether to allow CarPlay to display notifications of this type. Apps must be approved for CarPlay to make use of this feature.

Default: false
categorySummaryFormat
(optional)
string

A format string for the summary description used when the system groups the category’s notifications.

customDismissAction
(optional)
boolean

A boolean indicating whether to send actions for handling when the notification is dismissed (the user must explicitly dismiss the notification interface - ignoring a notification or flicking away a notification banner does not trigger this action).

Default: false
intentIdentifiers
(optional)
string[]

Array of Intent Class Identifiers. When a notification is delivered, the presence of an intent identifier lets the system know that the notification is potentially related to the handling of a request made through Siri.

Default: []
previewPlaceholder
(optional)
string

Customizable placeholder for the notification preview text. This is shown if the user has disabled notification previews for the app. Defaults to the localized iOS system default placeholder (Notification).

showSubtitle
(optional)
boolean

A boolean indicating whether to show the notification's subtitle, even if the user has disabled notification previews for the app.

Default: false
showTitle
(optional)
boolean

A boolean indicating whether to show the notification's title, even if the user has disabled notification previews for the app.

Default: false
Only for: 
Android

NotificationChannelInput

Type: RequiredBy<Omit<NotificationChannel, 'id' | 'audioAttributes' | 'sound'> & { audioAttributes: AudioAttributesInput, sound: string | null }, 'name' | 'importance'>

An object represents a notification channel to be set.

NotificationContent

An object represents notification's content.

NotificationContentIos | NotificationContentAndroid extended by:


NameTypeDescription
bodystring | null

Notification body - the main content of the notification.

dataRecord<string, any>

Data associated with the notification, not displayed

sound'default' | 'defaultCritical' | 'custom' | null-
subtitlestring | null

On Android: subText - the display depends on the device.

On iOS: subtitle - the bold text displayed between title and the rest of the content.

titlestring | null

Notification title - the bold text displayed above the rest of the content.

NotificationContentAndroid

See Android developer documentation for more information on specific fields.

NameTypeDescription
badge
(optional)
number

Application badge number associated with the notification.

color
(optional)
string

Accent color (in #AARRGGBB or #RRGGBB format) to be applied by the standard Style templates when presenting this notification.

priority
(optional)
AndroidNotificationPriority

Relative priority for this notification. Priority is an indication of how much of the user's valuable attention should be consumed by this notification. Low-priority notifications may be hidden from the user in certain situations, while the user might be interrupted for a higher-priority notification. The system will make a determination about how to interpret this priority when presenting the notification.

vibrationPattern
(optional)
number[]

The pattern with which to vibrate.

Only for: 
iOS

NotificationContentAttachmentIos

NameTypeDescription
hideThumbnail
(optional)
boolean-
identifierstring | null-
thumbnailClipArea
(optional)
{ height: number, width: number, x: number, y: number }-
thumbnailTime
(optional)
number-
typestring | null-
typeHint
(optional)
string-
urlstring | null-

NotificationContentInput

An object represents notification content that you pass in to presentNotificationAsync or as a part of NotificationRequestInput.

NameTypeDescription
attachments
(optional)
NotificationContentAttachmentIos[]Only for: 
iOS

The visual and audio attachments to display alongside the notification’s main content.

autoDismiss
(optional)
booleanOnly for: 
Android

If set to false, the notification will not be automatically dismissed when clicked. The setting will be used when the value is not provided or is invalid is set to true, and the notification will be dismissed automatically anyway. Corresponds directly to Android's setAutoCancel behavior.

See Android developer documentation for more details.

badge
(optional)
number

Application badge number associated with the notification.

body
(optional)
string | null

The main content of the notification.

categoryIdentifier
(optional)
stringOnly for: 
iOS

The identifier of the notification’s category.

color
(optional)
stringOnly for: 
Android

Accent color (in #AARRGGBB or #RRGGBB format) to be applied by the standard Style templates when presenting this notification.

data
(optional)
Record<string, any>

Data associated with the notification, not displayed.

launchImageName
(optional)
string

The name of the image or storyboard to use when your app launches because of the notification.

priority
(optional)
stringOnly for: 
Android

Relative priority for this notification. Priority is an indication of how much of the user's valuable attention should be consumed by this notification. Low-priority notifications may be hidden from the user in certain situations, while the user might be interrupted for a higher-priority notification. The system will make a determination about how to interpret this priority when presenting the notification.

sound
(optional)
boolean | string-
sticky
(optional)
booleanOnly for: 
Android

If set to true, the notification cannot be dismissed by swipe. This setting defaults to false if not provided or is invalid. Corresponds directly do Android's isOngoing behavior. In Firebase terms this property of a notification is called sticky.

See Android developer documentation and Firebase documentation for more details.

subtitle
(optional)
string | null

On Android: subText - the display depends on the device.

On iOS: subtitle - the bold text displayed between title and the rest of the content.

title
(optional)
string | null

Notification title - the bold text displayed above the rest of the content.

vibrate
(optional)
number[]Only for: 
Android

The pattern with which to vibrate.

NotificationContentIos

See Apple documentation for more information on specific fields.

NameTypeDescription
attachmentsNotificationContentAttachmentIos[]

The visual and audio attachments to display alongside the notification’s main content.

badgenumber | null

The number that your app’s icon displays.

categoryIdentifierstring | null

The identifier of the notification’s category.

launchImageNamestring | null

The name of the image or storyboard to use when your app launches because of the notification.

summaryArgument
(optional)
string | null

The text the system adds to the notification summary to provide additional context.

summaryArgumentCount
(optional)
number

The number the system adds to the notification summary when the notification represents multiple items.

targetContentIdentifier
(optional)
string

The value your app uses to determine which scene to display to handle the notification.

threadIdentifierstring | null

The identifier that groups related notifications.

NotificationHandlingError

Literal Type: multiple types

Acceptable values are: NotificationTimeoutError | Error

NotificationTrigger

Literal Type: multiple types

A union type containing different triggers which may cause the notification to be delivered to the application.

Acceptable values are: PushNotificationTrigger | CalendarNotificationTrigger | LocationNotificationTrigger | TimeIntervalNotificationTrigger | DailyNotificationTrigger | WeeklyNotificationTrigger | YearlyNotificationTrigger | UnknownNotificationTrigger

NotificationTriggerInput

Literal Type: multiple types

A type represents possible triggers with which you can schedule notifications. A null trigger means that the notification should be scheduled for delivery immediately.

Acceptable values are: null | ChannelAwareTriggerInput | SchedulableNotificationTriggerInput

PermissionExpiration

Literal Type: multiple types

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never' | number

PermissionHookOptions

Literal Type: multiple types

Acceptable values are: PermissionHookBehavior | Options

PushNotificationTrigger

An object represents a notification delivered by a push notification system.

On Android under remoteMessage field a JS version of the Firebase RemoteMessage may be accessed. On iOS under payload you may find full contents of UNNotificationContent's userInfo, for example remote notification payload On web there is no extra data.

NameTypeDescription
payload
(optional)
Record<string, unknown>-
remoteMessage
(optional)
FirebaseRemoteMessage-
type'push'-

PushTokenListener()

A function accepting a device push token (DevicePushToken) as an argument.

Note: You should not call getDevicePushTokenAsync inside this function, as it triggers the listener and may lead to an infinite loop.

NameTypeDescription
tokenDevicePushToken-

RequiredBy

Literal Type: multiple types

Acceptable values are: Partial<Omit<T, K>> | Required<Pick<T, K>>

SchedulableNotificationTriggerInput

Literal Type: multiple types

A type represents time-based, schedulable triggers. For these triggers you can check the next trigger date with getNextTriggerDateAsync.

Acceptable values are: DateTriggerInput | TimeIntervalTriggerInput | DailyTriggerInput | WeeklyTriggerInput | YearlyTriggerInput | CalendarTriggerInput

Subscription

NameTypeDescription
remove() => void

A method to unsubscribe the listener.

WebDevicePushTokenKeys

NameTypeDescription
authstring-
p256dhstring-

Enums

AndroidAudioContentType

AndroidAudioContentType Values

UNKNOWN

AndroidAudioContentType.UNKNOWN = 0

SPEECH

AndroidAudioContentType.SPEECH = 1

MUSIC

AndroidAudioContentType.MUSIC = 2

MOVIE

AndroidAudioContentType.MOVIE = 3

SONIFICATION

AndroidAudioContentType.SONIFICATION = 4

AndroidAudioUsage

AndroidAudioUsage Values

UNKNOWN

AndroidAudioUsage.UNKNOWN = 0

MEDIA

AndroidAudioUsage.MEDIA = 1

VOICE_COMMUNICATION

AndroidAudioUsage.VOICE_COMMUNICATION = 2

VOICE_COMMUNICATION_SIGNALLING

AndroidAudioUsage.VOICE_COMMUNICATION_SIGNALLING = 3

ALARM

AndroidAudioUsage.ALARM = 4

NOTIFICATION

AndroidAudioUsage.NOTIFICATION = 5

NOTIFICATION_RINGTONE

AndroidAudioUsage.NOTIFICATION_RINGTONE = 6

NOTIFICATION_COMMUNICATION_REQUEST

AndroidAudioUsage.NOTIFICATION_COMMUNICATION_REQUEST = 7

NOTIFICATION_COMMUNICATION_INSTANT

AndroidAudioUsage.NOTIFICATION_COMMUNICATION_INSTANT = 8

NOTIFICATION_COMMUNICATION_DELAYED

AndroidAudioUsage.NOTIFICATION_COMMUNICATION_DELAYED = 9

NOTIFICATION_EVENT

AndroidAudioUsage.NOTIFICATION_EVENT = 10

ASSISTANCE_ACCESSIBILITY

AndroidAudioUsage.ASSISTANCE_ACCESSIBILITY = 11

ASSISTANCE_NAVIGATION_GUIDANCE

AndroidAudioUsage.ASSISTANCE_NAVIGATION_GUIDANCE = 12

ASSISTANCE_SONIFICATION

AndroidAudioUsage.ASSISTANCE_SONIFICATION = 13

GAME

AndroidAudioUsage.GAME = 14

AndroidImportance

AndroidImportance Values

UNKNOWN

AndroidImportance.UNKNOWN = 0

UNSPECIFIED

AndroidImportance.UNSPECIFIED = 1

NONE

AndroidImportance.NONE = 2

MIN

AndroidImportance.MIN = 3

LOW

AndroidImportance.LOW = 4

Deprecated. Use DEFAULT instead.

DEEFAULT

AndroidImportance.DEEFAULT = 5

DEFAULT

AndroidImportance.DEFAULT = 5

HIGH

AndroidImportance.HIGH = 6

MAX

AndroidImportance.MAX = 7

AndroidNotificationPriority

An enum corresponding to values appropriate for Android's Notification#priority field.

AndroidNotificationPriority Values

DEFAULT

AndroidNotificationPriority.DEFAULT = "default"

HIGH

AndroidNotificationPriority.HIGH = "high"

LOW

AndroidNotificationPriority.LOW = "low"

MAX

AndroidNotificationPriority.MAX = "max"

MIN

AndroidNotificationPriority.MIN = "min"

AndroidNotificationVisibility

AndroidNotificationVisibility Values

UNKNOWN

AndroidNotificationVisibility.UNKNOWN = 0

PUBLIC

AndroidNotificationVisibility.PUBLIC = 1

PRIVATE

AndroidNotificationVisibility.PRIVATE = 2

SECRET

AndroidNotificationVisibility.SECRET = 3

IosAlertStyle

IosAlertStyle Values

NONE

IosAlertStyle.NONE = 0

IosAlertStyle.BANNER = 1

ALERT

IosAlertStyle.ALERT = 2

IosAllowsPreviews

IosAllowsPreviews Values

NEVER

IosAllowsPreviews.NEVER = 0

ALWAYS

IosAllowsPreviews.ALWAYS = 1

WHEN_AUTHENTICATED

IosAllowsPreviews.WHEN_AUTHENTICATED = 2

IosAuthorizationStatus

IosAuthorizationStatus Values

NOT_DETERMINED

IosAuthorizationStatus.NOT_DETERMINED = 0

DENIED

IosAuthorizationStatus.DENIED = 1

AUTHORIZED

IosAuthorizationStatus.AUTHORIZED = 2

PROVISIONAL

IosAuthorizationStatus.PROVISIONAL = 3

EPHEMERAL

IosAuthorizationStatus.EPHEMERAL = 4

PermissionStatus

PermissionStatus Values

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.

Expo 中文网 - 粤ICP备13048890号