iOS 및 Android용 Resact Native 응용 프로그램에서 인터넷 연결을 확인하는 방법
나는 Resact Native 애플리케이션을 가지고 있고 앱이 처음 시작할 때, 그리고 그 이후에 계속적으로 인터넷 연결이 활성화되어 있는지 확인하는 기능을 추가하려고 한다.
인터넷 연결이 없으면 '다시 시도하라'는 버튼과 함께 '인터넷 연결이 감지되지 않는다'는 메시지를 표시하고, 인터넷 연결이 있으면 페이지(웹뷰)를 로드하려고 한다.
나는 또한 iOS와 Android 기기 모두를 지원하고자 한다; 나는 이것을 독립적으로 연구했고 GitHub에서 몇 개의 도서관을 찾았다.그러나 많은 경우 Android 매니페스트 XML에 권한을 추가하는 추가 단계가 필요하지만 내 앱에는 Android 매니페스트 XML 파일이 표시되지 않는데 왜 Android에만 매니페스트가 필요한가?
어떤 도움이라도 감사히 여기며, 몸조심하십시오.
이 https://reactnativeforyou.com/how-to-check-internet-connectivity-in-react-native-android-and-ios/ 링크를 읽어 보십시오.
import React, { Component } from "react";
import { View, Text, Button, Alert, NetInfo, Platform } from "react-native";
export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {};
}
CheckConnectivity = () => {
// For Android devices
if (Platform.OS === "android") {
NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
Alert.alert("You are online!");
} else {
Alert.alert("You are offline!");
}
});
} else {
// For iOS devices
NetInfo.isConnected.addEventListener(
"connectionChange",
this.handleFirstConnectivityChange
);
}
};
handleFirstConnectivityChange = isConnected => {
NetInfo.isConnected.removeEventListener(
"connectionChange",
this.handleFirstConnectivityChange
);
if (isConnected === false) {
Alert.alert("You are offline!");
} else {
Alert.alert("You are online!");
}
};
render() {
return (
<View>
<Button
onPress={() => this.CheckConnectivity()}
title="Check Internet Connectivity"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
);
}
}
나는 오늘 우연히 이 문제에 부딪혔고 내가 가장 좋다고 생각하는 해결책을 찾았다.네트워크 변경사항을 지속적으로 검색하여 표시한다.
엑스포 설치 @react-native-community/netinfo로 테스트해 봤는데, 완벽하게 작동했어.
import {useNetInfo} from "@react-native-community/netinfo";
import {View, Text} from "react-native";
const YourComponent = () => {
const netInfo = useNetInfo();
return (
<View>
<Text>Type: {netInfo.type}</Text>
<Text>Is Connected? {netInfo.isConnected.toString()}</Text>
</View>
);
};
이 질문은 너무 지나쳐서 아무도 다른 기존의 답을 보는 것 같지 않다.
"@react-native-community/netinfo" 라이브러리를 사용하십시오.NetInfo는 리액티브의 일부였지만 코어에서 분리되었다.네트워크 상태 변경을 관찰하려면 제공된 addEventListener 방법을 사용하십시오.
import NetInfo from "@react-native-community/netinfo";
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
const unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
// Unsubscribe
unsubscribe();
react-react-reason은 netinfo라는 라이브러리를 제공하십시오. https://github.com/react-native-community/react-native-netinfo에서 확인하십시오.
연결성과 종류를 확인할 수 있는 api를 제공한다.
NB: RN < 0.60: https://facebook.github.io/react-native/docs/netinfo.html을 사용하는 경우
NetInfo가 React-Native에서 제거됨.이제 'react-native' 대신 'react-native-netinfo'에서 설치, 수입할 수 있게 됐다.https://github.com/react-native-community/react-native-netinfo을 참조하십시오.
NetworkUtils.js 생성
import NetInfo from "@react-native-community/netinfo";
export default class NetworkUtils {
static async isNetworkAvailable() {
const response = await NetInfo.fetch();
return response.isConnected;
}}
이런 곳이라면 어디든 사용
const isConnected = await NetworkUtils.isNetworkAvailable()
여기 당신의 앱이 인터넷에 접속할 수 있는지 확인하는 방법에 대한 최신 솔루션이 있다.
공식 설치부터 시작NetInfo
커뮤니티 패키지:
yarn add @react-native-community/netinfo
그리고 그 새끼.
import { Platform } from "react-native";
import NetInfo from "@react-native-community/netinfo";
...
const checkConnectivity = (): Promise<boolean | null> => {
return new Promise(resolve => {
// For Android devices
if (Platform.OS === "android") {
NetInfo.fetch().then(state => {
resolve(state.isInternetReachable);
});
} else {
// For iOS devices
const unsubscribe = NetInfo.addEventListener(state => {
unsubscribe();
resolve(state.isInternetReachable);
});
}
});
};
...
그리고 그것은 사용법이다.
...
const hasInternet = await checkConnectivity();
if(hasInternet) {
// My app can reach the internet
}
else {
// Can't connect to the internet. Too bad!
}
엑스포의 경우:
import NetInfo from "@react-native-community/netinfo";
export const checkConnected = () => {
return NetInfo.fetch().then((state) => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
return state.isConnected;
});
};
이 문서를 확인하십시오: https://docs.expo.dev/versions/lastest/sdk/netinfo/
나는 이 코드를 스플래시 화면에 추가해서 NetInfo가 "isConnected : false"를 반환할 때 네트워크가 연결되어 있으면 Try Again(다시 시도) 버튼을 표시해서 내비게이션이 홈 화면으로 대체된다.
내 스플래시 화면이다.
import React, { useEffect, useState } from "react";
...
import NetInfo from "@react-native-community/netinfo";
const Splash = (props) => {
const [network, setNetwork] = useState('')
const [loading, setLoading] = useState(false);
useEffect(() => {
unsubscribe()
}, []);
function unsubscribe() {
NetInfo.fetch().then(state => {
setNetwork(state)
setTimeout(function () {
if (state.isConnected) {
// any thing you want to load before navigate home screen
} else {
setLoading(false)
}
}, 500);
})
};
return (
<View style={{
flex: 1,
backgroundColor: global.bgBody,
justifyContent: 'center',
alignItems: 'center'
}}>
<Image
source={Logo}
style={{
width: 150,
height: 123,
}}
/>
{!network?.isConnected || loading ? <View style={{ marginTop: 30 }}>
<Description text={`Please check your internet connection and try again`} />
<Button
title="Try Again"
onPress={() => {
setLoading(true)
unsubscribe()
}}
loading={loading}
/>
</View> : null}
</View>
);
};
export default Splash;
Android 매니페스트 파일은 다음과 같다: \android\app\src\main\AndroidManifest.xml.이 라이브러리를 사용하여 https://github.com/react-native-community/react-native-netinfo을 추가로 요구하십시오.
'programing' 카테고리의 다른 글
Vue 프로젝트의 보기와 구성 요소 폴더 간의 차이점은? (0) | 2022.04.03 |
---|---|
페이지 새로 고침 시 NextJS에서 Redex 상태를 올바르게 수산화하는 방법 (0) | 2022.04.03 |
vue 라우팅: 올바른 라우팅/프로토콜이 있는 동일한 페이지의 목록-프로토콜 보기 (0) | 2022.04.03 |
python에서 float를 정수로 변환하는 가장 안전한 방법? (0) | 2022.04.03 |
ESC 키를 누르면 대화 상자 닫기 (0) | 2022.04.03 |