개발자를 향해...
[React Native로 날씨앱 만들기] #1.3 Asking for Permissions ~ #1.4 Getting the Weather 본문
[React Native로 날씨앱 만들기] #1.3 Asking for Permissions ~ #1.4 Getting the Weather
eugeneHwang1124 2021. 2. 26. 15:11이 글은 노마드 코더 님의 [ React Native로 날씨앱 만들기 ] 를 수강하며 작성하였습니다.
#1.3 Asking for Permissions
권한 허용을 위해 try catch 문에 권한 허용을 받은 뒤 콘솔에 출력해보자.
import React from "react";
import { Alert } from "react-native";
import Loading from "./Loading";
import * as Location from "expo-location";
export default class extends React.Component {
getLocation = async () => {
//console.log("here!!!!!")
try{
const response=await Location.requestPermissionsAsync();
console.log(response);
console.log("2");
const location=await Location.getCurrentPositionAsync();
console.log(location);
}catch(error){ //사용자가 권한을 주지 않았을 때
Alert.alert("Can't find you.", "So sad");
}
}
componentDidMount(){
this.getLocation();
}
render(){
return <Loading />;
}
}
권한 허용을 물어보다가 사용자가 권한을 주지 않으면 다음과 같이 알림이 뜬다.
ios에서는 경고창이 다르게 보일 것이다. 이제 권한 허용을 하고 콘솔창을 확인해보자.
두번째 object가 우리가 출력한 location 오브젝트의 값이다. 여기서 coords를 가져오자. location 선언 및 호출 부분을 아래와 같이 바꾼다.
const {coords}=await Location.getCurrentPositionAsync();
console.log(coords.latitude, coords.longitude);
이제 이 값들을 rename 하자. 그리고 로딩하는 동안 위치 값을 가져오도록 코드를 작성한다.
import React from "react";
import { Alert } from "react-native";
import Loading from "./Loading";
import * as Location from "expo-location";
export default class extends React.Component {
state={
isLoading:true
}
getLocation = async () => {
try{
const response=await Location.requestPermissionsAsync();
const {coords:{latitude, longitude}}=await Location.getCurrentPositionAsync();
this.setState({isLoading:false});
}catch(error){ //사용자가 권한을 주지 않았을 때
Alert.alert("Can't find you.", "So sad");
}
}
componentDidMount(){
this.getLocation();
}
render(){
const {isLoading}=this.state;
return isLoading ?<Loading />:null;
}
}
#1.4 Getting the Weather
weather api에서 api를 가져와서 날씨 정보를 받아오자. openweathermap.org/api에 가서 api key를 가져온다. 가져온 키를 app.js에 변수로 저장해준다.
openweathermap.org/current 로 들어가면 현재 날씨 정보를 가져오는 다양한 방법이 있는데 우리는 By geographic coordinate를 통해 가져온다. Example of using API key in API call에서 주소에 api 키 값을 넣으면 날씨 데이터가 object로 가져와지는것을 확인할 수 있는데 이 가져온 값을 어플리케이션에 fetch하기 위해 axios를 활용하자.
이를 위해 axios를 설치한다.(npm i axios / yarn add axios)
import React from "react";
import { Alert } from "react-native";
import Loading from "./Loading";
import * as Location from "expo-location";
import axios from "axios";
const API_KEY="347c05ed278306843f271a8ea013fe29";
export default class extends React.Component {
state={
isLoading:true
}
getWeather = async (latitude, longitude) => {
const { data } = await axios.get(`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&APPID=${API_KEY}`);
console.log(data);
};
getLocation = async () => {
try{
const response=await Location.requestPermissionsAsync();
const {coords:{latitude, longitude}}=await Location.getCurrentPositionAsync();
this.getWeather(latitude, longitude);
this.setState({isLoading:false});
}catch(error){ //사용자가 권한을 주지 않았을 때
Alert.alert("Can't find you.", "So sad");
}
}
componentDidMount(){
this.getLocation();
}
render(){
const {isLoading}=this.state;
return isLoading ?<Loading />:null;
}
}
실행하면 데이터를 잘 받아오는 것을 볼 수 있다.