> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/network-environment/network.md).

# 网络

### 1. 检查网络连接状态（`getNetworkStatus`)

`getNetworkStatus`是获取设备当前网络连接状态的函数。返回值是 `NetworkStatus` 类型，表示是否连接互联网以及连接类型（Wi-Fi、移动数据等）。取值如下之一。

* `OFFLINE`：未连接到互联网的状态。
* `WIFI`：已连接到 Wi-Fi 的状态。
* `2G`：已连接到 2G 网络的状态。
* `3G`：已连接到 3G 网络的状态。
* `4G`：已连接到 4G 网络的状态。
* `5G`：已连接到 5G 网络的状态。
* `WWAN`：已连接互联网，但无法得知连接类型（Wi-Fi、2G\~5G）的状态。此状态只能在 iOS 上确认。
* `UNKNOWN`：无法得知互联网连接状态的状态。此状态只能在 Android 上确认。

**签名**

```typescript
function getNetworkStatus(): Promise<NetworkStatus>;
```

**返回值**

* `Promise<NetworkStatus>`

  返回网络状态。

**示例**

这是获取网络连接状态并显示到屏幕上的示例。

```tsx
import { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { getNetworkStatus, NetworkStatus } from '@apps-in-toss/framework';

function GetNetworkStatus() {
  const [status, setStatus] = useState<NetworkStatus | ''>('');

  useEffect(() => {
    async function fetchStatus() {
      const networkStatus = await getNetworkStatus();
      setStatus(networkStatus);
    }

    fetchStatus();
  }, []);

  return (
    <View>
      <Text>当前网络状态：{status}</Text>
    </View>
  );
}
```

**体验示例应用**

[apps-in-toss-examples](https://github.com/toss/apps-in-toss-examples) 在仓库中 [with-network-status](https://github.com/toss/apps-in-toss-examples/tree/main/with-network-status) 下载代码，或扫描下方二维码亲自体验。

二维码链接：intoss\://with-network-status

***

### 2. 进行 HTTP 通信

介绍在 Bedrock 中进行网络通信的方法。

**使用 Fetch API**

在 Bedrock 中，像 React Native 一样 [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)可以用于网络通信。Fetch API 是一种标准 Web API，可以简单实现异步网络请求。

以下是使用获取“待办事项列表”的 API，在“待办事项”完成时显示删除线的示例。

{% tabs %}
{% tab title="pages/index.tsx" %}

```tsx
import { createRoute } from '@granite-js/react-native';
import { useCallback, useState } from 'react';
import { Button, ScrollView } from 'react-native';
import { Todo, TodoItem } from './Todo';

export const Route = createRoute('/', {
  component: Index,
});

function Index() {
  const [todos, setTodos] = useState<TodoItem[]>([]);
  // [!code highlight:10]
  const handlePress = useCallback(async () => {
    /**
     * 从 JSONPlaceholder API 获取待办事项数据。
     * @link https://jsonplaceholder.typicode.com/
     */
    const result = await fetch('https://jsonplaceholder.typicode.com/todos');
    const json = await result.json(); // 将响应数据转换为 JSON。
    setTodos(json); // 将获取到的数据保存到状态中。
  }, []);

  return (
    <>
      <Button title="查看待办事项列表" onPress={handlePress} />
      <ScrollView>
        {todos.map((todo) => {
          return <Todo key={todo.id} id={todo.id} title={todo.title} completed={todo.completed} />;
        })}
      </ScrollView>
    </>
  );
}
```

{% endtab %}

{% tab title="Todo.tsx" %}

```tsx
import { Flex } from '@granite-js/react-native';
import { Text } from 'react-native';

export interface TodoItem {
  title: string; // 待办事项标题
  id: number; // 待办事项 ID
  completed: boolean; // 是否完成
}

export function Todo({ title, id, completed: done }: TodoItem) {
  return (
    <Flex direction="row" key={id}>
      <Flex.CenterVertical
        style={{
          minWidth: 30,
        }}
      >
        <Text style={{ fontSize: 24 }}>{id}.</Text>
      </Flex.CenterVertical>
      <Flex.CenterVertical>
        <Text
          style={{
            fontSize: 16,
            textDecorationColor: 'red', // 删除线颜色
            textDecorationLine: done ? 'line-through' : 'none', // 根据是否完成显示删除线
          }}
        >
          {title}
        </Text>
      </Flex.CenterVertical>
    </Flex>
  );
}
```

{% endtab %}
{% endtabs %}

从示例视频可以看到，点击按钮后会发生网络请求，屏幕上会显示待办事项列表。发生网络请求时，可以在网络检查器中查看请求和响应。

观看视频

**使用其他库**

React Native 支持 [XMLHttpRequest API](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)。因此，也可以使用使用该 API 的第三方网络库。

详细内容请参阅 [React Native 官方文档](https://reactnative.dev/docs/0.72/network#using-other-networking-libraries)。

***

### 3. 获取服务器时间（`getServerTime`)

`getServerTime` 函数是获取以 Toss App 服务器为基准的当前时间的 API。它返回的不是设备时间，而是 **服务器时间（Server Time）** ，因此有助于防止因客户端时间篡改而导致的奖励重复领取或作弊。

可用于签到检查、活动期间验证、判断是否可领取奖励等 **对时间可靠性要求较高的逻辑**。

{% hint style="info" %}
**请参考**

* 返回的时间是 **Unix 时间戳（毫秒单位）** 格式。
* 在不支持的应用版本中， `undefined`可能会返回。
* 使用前 `getServerTime.isSupported()`做 **建议先确认版本是否支持**。
  {% endhint %}

**签名**

```typescript
function getServerTime(): Promise<number | undefined>;
```

**返回值**

* `Promise<number | undefined>`

  以 Unix 时间戳毫秒单位返回 Toss App 服务器当前时间。（例如： `1705123456789`）在不支持的版本中 `undefined`会返回。

**示例**

{% tabs %}
{% tab title="React" %}

```tsx
import { getServerTime } from '@apps-in-toss/web-framework';

async function checkRewardEligibility() {
  // 建议先执行版本检查
  if (!getServerTime.isSupported()) {
    console.log('此功能在该版本中不受支持。');
    return;
  }

  const serverTime = await getServerTime();
  const rewardDeadline = 1705200000000;

  if (serverTime && serverTime > rewardDeadline) {
    console.log('奖励领取期限已过。');
  }
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { getServerTime } from '@apps-in-toss/framework';

async function checkRewardEligibility() {
  // 建议先执行版本检查
  if (!getServerTime.isSupported()) {
    console.log('此功能在该版本中不受支持。');
    return;
  }

  const serverTime = await getServerTime();
  const rewardDeadline = 1705200000000;

  if (serverTime && serverTime > rewardDeadline) {
    console.log('奖励领取期限已过。');
  }
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/network-environment/network.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
