如何在 React Native iOS 模块中访问 AppDelegate 方法

How to access AppDelegate methods in react native iOS module

我正在构建一个 iOS 模块并想连接到 AppDelegate 方法,例如 applicationWillResignActive,我该如何实现?

您正在尝试使用 applicationWillResignActive 每次应用程序进入后台时都会触发该方法。

您可以通过使用 AppState 在 React Native 中实现这一点 可以告诉您应用程序是在前台还是后台,并在状态发生变化时通知您。

示例:

import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";

const AppStateExample = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    const subscription = AppState.addEventListener("change", nextAppState => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        console.log("App has come to the foreground!");
      }

      appState.current = nextAppState;
      setAppStateVisible(appState.current);
      console.log("AppState", appState.current);
    });

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

  return (
    <View style={styles.container}>
      <Text>Current state is: {appStateVisible}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default AppStateExample;