내일배움카드로 스파르타 코딩에서 강의를 듣기 시작한지 두달이 다 되었네요.
중간중간 끊어서 듣고, 귀찮아서 안한날도 있고, 오늘은 5주차 공부내용 정리하고 복습을 더 해야겠습니다.
일단 내용정리 먼저, 그다음에 복습 ㅋㅋ
5주차 구글 애드몹 설정 관련 강의
app.json 하단 추가 부분
"ios": {
"supportsTablet": true,
"buildNumber": "1.0.0",
"bundleIdentifier": "com.myhoneytip.gun",
"config": {
"googleMobileAdsAppId": ""
}
},
"android": {
"package": "com.myhoneytip.gun",
"versionCode": 1,
"config": {
"googleMobileAdsAppId": ""
}
},
애드몹 가로배너 생성
Mainpage.js
import React,{useState,useEffect} from 'react';
import { StyleSheet, Text, View, Image, TouchableOpacity, ScrollView} from 'react-native';
const main = 'https://storage.googleapis.com/sparta-image.appspot.com/lecture/main.png'
import data from '../data.json';
import Card from '../components/Card';
import Loading from '../components/Loading';
import { StatusBar } from 'expo-status-bar';
import * as Location from "expo-location";
import axios from "axios"
import {firebase_db} from "../firebaseConfig"
import {
setTestDeviceIDAsync,
AdMobBanner,
AdMobInterstitial,
PublisherBanner,
AdMobRewarded
} from 'expo-ads-admob';
export default function MainPage({navigation,route}) {
//useState 사용법
//[state,setState] 에서 state는 이 컴포넌트에서 관리될 상태 데이터를 담고 있는 변수
//setState는 state를 변경시킬때 사용해야하는 함수
//모두 다 useState가 선물해줌
//useState()안에 전달되는 값은 state 초기값
const [state,setState] = useState([])
const [cateState,setCateState] = useState([])
//날씨 데이터 상태관리 상태 생성!
const [weather, setWeather] = useState({
temp : 0,
condition : ''
})
//하단의 return 문이 실행되어 화면이 그려진다음 실행되는 useEffect 함수
//내부에서 data.json으로 부터 가져온 데이터를 state 상태에 담고 있음
const [ready,setReady] = useState(true)
useEffect(()=>{
navigation.setOptions({
title:'나만의 꿀팁'
})
//뒤의 1000 숫자는 1초를 뜻함
//1초 뒤에 실행되는 코드들이 담겨 있는 함수
setTimeout(()=>{
firebase_db.ref('/tip').once('value').then((snapshot) => {
console.log("파이어베이스에서 데이터 가져왔습니다!!")
let tip = snapshot.val();
setState(tip)
setCateState(tip)
getLocation()
setReady(false)
});
// getLocation()
// setState(data.tip)
// setCateState(data.tip)
// setReady(false)
},1000)
},[])
const getLocation = async () => {
//수많은 로직중에 에러가 발생하면
//해당 에러를 포착하여 로직을 멈추고,에러를 해결하기 위한 catch 영역 로직이 실행
try {
//자바스크립트 함수의 실행순서를 고정하기 위해 쓰는 async,await
await Location.requestForegroundPermissionsAsync();
const locationData= await Location.getCurrentPositionAsync();
console.log(locationData)
console.log(locationData['coords']['latitude'])
console.log(locationData['coords']['longitude'])
const latitude = locationData['coords']['latitude']
const longitude = locationData['coords']['longitude']
const API_KEY = "cfc258c75e1da2149c33daffd07a911d";
const result = await axios.get(
`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
);
console.log(result)
const temp = result.data.main.temp;
const condition = result.data.weather[0].main
console.log(temp)
console.log(condition)
//오랜만에 복습해보는 객체 리터럴 방식으로 딕셔너리 구성하기!!
//잘 기억이 안난다면 1주차 강의 6-5를 다시 복습해보세요!
setWeather({
temp,condition
})
} catch (error) {
//혹시나 위치를 못가져올 경우를 대비해서, 안내를 준비합니다
Alert.alert("위치를 찾을 수가 없습니다.", "앱을 껏다 켜볼까요?");
}
}
const category = (cate) => {
if(cate == "전체보기"){
//전체보기면 원래 꿀팁 데이터를 담고 있는 상태값으로 다시 초기화
setCateState(state)
}else{
setCateState(state.filter((d)=>{
return d.category == cate
}))
}
}
//data.json 데이터는 state에 담기므로 상태에서 꺼내옴
// let tip = state.tip;
let todayWeather = 10 + 17;
let todayCondition = "흐림"
//return 구문 밖에서는 슬래시 두개 방식으로 주석
return ready ? <Loading/> : (
/*
return 구문 안에서는 {슬래시 + * 방식으로 주석
*/
<ScrollView style={styles.container}>
<StatusBar style="light" />
{/* <Text style={styles.title}>나만의 꿀팁</Text> */}
<Text style={styles.weather}>오늘의 날씨: {weather.temp + '°C ' + weather.condition} </Text>
<TouchableOpacity style={styles.aboutButton} onPress={()=>{navigation.navigate('AboutPage')}}>
<Text style={styles.aboutButtonText}>소개 페이지</Text>
</TouchableOpacity>
<Image style={styles.mainImage} source={{uri:main}}/>
<ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
<TouchableOpacity style={styles.middleButtonAll} onPress={()=>{category('전체보기')}}><Text style={styles.middleButtonTextAll}>전체보기</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton01} onPress={()=>{category('생활')}}><Text style={styles.middleButtonText}>생활</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton02} onPress={()=>{category('재테크')}}><Text style={styles.middleButtonText}>재테크</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton03} onPress={()=>{category('반려견')}}><Text style={styles.middleButtonText}>반려견</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton04} onPress={()=>{navigation.navigate('LikePage')}}><Text style={styles.middleButtonText}>꿀팁 찜</Text></TouchableOpacity>
</ScrollView>
<View style={styles.cardContainer}>
{/* 하나의 카드 영역을 나타내는 View */}
{
cateState.map((content,i)=>{
return (<Card content={content} key={i} navigation={navigation}/>)
})
}
</View>
{/*
ca-app-pub-5579008343368676/9202552776
ca-app-pub-5579008343368676/6885179499
*/}
{Platform.OS === 'ios' ? (
<AdMobBanner
bannerSize="fullBanner"
servePersonalizedAds={true}
adUnitID="ca-app-pub-5579008343368676/6885179499"
style={styles.banner}
/>
) : (
<AdMobBanner
bannerSize="fullBanner"
servePersonalizedAds={true}
adUnitID="ca-app-pub-5579008343368676/9202552776"
style={styles.banner}
/>
)}
</ScrollView>)
}
const styles = StyleSheet.create({
container: {
//앱의 배경 색
backgroundColor: '#fff',
},
title: {
//폰트 사이즈
fontSize: 20,
//폰트 두께
fontWeight: '700',
//위 공간으로 부터 이격
marginTop:50,
//왼쪽 공간으로 부터 이격
marginLeft:20
},
weather:{
alignSelf:"flex-end",
paddingRight:20
},
mainImage: {
//컨텐츠의 넓이 값
width:'90%',
//컨텐츠의 높이 값
height:200,
//컨텐츠의 모서리 구부리기
borderRadius:10,
marginTop:20,
//컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
//각 속성의 값들은 공식문서에 고대로~ 나와 있음
alignSelf:"center"
},
middleContainer:{
marginTop:20,
marginLeft:10,
height:60
},
middleButtonAll: {
width:100,
height:50,
padding:15,
backgroundColor:"#20b2aa",
borderColor:"deeppink",
borderRadius:15,
margin:7
},
middleButton01: {
width:100,
height:50,
padding:15,
backgroundColor:"#fdc453",
borderColor:"deeppink",
borderRadius:15,
margin:7
},
middleButton02: {
width:100,
height:50,
padding:15,
backgroundColor:"#fe8d6f",
borderRadius:15,
margin:7
},
middleButton03: {
width:100,
height:50,
padding:15,
backgroundColor:"#9adbc5",
borderRadius:15,
margin:7
},
middleButton04: {
width:100,
height:50,
padding:15,
backgroundColor:"#f886a8",
borderRadius:15,
margin:7
},
middleButtonText: {
color:"#fff",
fontWeight:"700",
//텍스트의 현재 위치에서의 정렬
textAlign:"center"
},
middleButtonTextAll: {
color:"#fff",
fontWeight:"700",
//텍스트의 현재 위치에서의 정렬
textAlign:"center"
},
cardContainer: {
marginTop:10,
marginLeft:10
},
aboutButton: {
backgroundColor:"pink",
width:100,
height:40,
borderRadius:10,
alignSelf:"flex-end",
marginRight:20,
marginTop:10
},
aboutButtonText: {
color:"#fff",
textAlign:"center",
marginTop:10
},
banner:{
width:"100%",
height:100
}
});
애드몹 전면 배너 생성
Card.js
import React, { useEffect } from 'react';
import {View, Image, Text, StyleSheet,TouchableOpacity,Platform} from 'react-native'
import {
setTestDeviceIDAsync,
AdMobBanner,
AdMobInterstitial,
PublisherBanner,
AdMobRewarded
} from 'expo-ads-admob';
//MainPage로 부터 navigation 속성을 전달받아 Card 컴포넌트 안에서 사용
export default function Card({content,navigation}){
useEffect(()=>{
// Card.js에 들어오자마자 전면 광고 준비하느라 useEffect에 설정
//애드몹도 외부 API 이므로 실행 순서를 지키기위해 async/await 사용!
//안드로이드와 IOS 각각 광고 준비 키가 다르기 때문에 디바이스 성격에 따라 다르게 초기화 시켜줘야 합니다.
Platform.OS === 'ios' ? AdMobInterstitial.setAdUnitID("ca-app-pub-5579008343368676/6838730428") : AdMobInterstitial.setAdUnitID("ca-app-pub-5579008343368676/4903859898")
AdMobInterstitial.addEventListener("interstitialDidLoad", () =>
console.log("interstitialDidLoad")
);
AdMobInterstitial.addEventListener("interstitialDidFailToLoad", () =>
console.log("interstitialDidFailToLoad")
);
AdMobInterstitial.addEventListener("interstitialDidOpen", () =>
console.log("interstitialDidOpen")
);
AdMobInterstitial.addEventListener("interstitialDidClose", () => {
//광고가 끝나면 다음 코드 줄이 실행!
console.log("interstitialDidClose")
});
},[])
const goDetail = async () =>{
try {
await AdMobInterstitial.requestAdAsync({ servePersonalizedAds: true});
await AdMobInterstitial.showAdAsync();
await navigation.navigate('DetailPage',{idx:content.idx})
} catch (error) {
console.log(error)
await navigation.navigate('DetailPage',{idx:content.idx})
}
}
return(
//카드 자체가 버튼역할로써 누르게되면 상세페이지로 넘어가게끔 TouchableOpacity를 사용
<TouchableOpacity style={styles.card} onPress={()=>{goDetail()}}>
<Image style={styles.cardImage} source={{uri:content.image}}/>
<View style={styles.cardText}>
<Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
<Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
<Text style={styles.cardDate}>{content.date}</Text>
</View>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
card:{
flex:1,
flexDirection:"row",
margin:10,
borderBottomWidth:0.5,
borderBottomColor:"#eee",
paddingBottom:10
},
cardImage: {
flex:1,
width:100,
height:100,
borderRadius:10,
},
cardText: {
flex:2,
flexDirection:"column",
marginLeft:10,
},
cardTitle: {
fontSize:20,
fontWeight:"700"
},
cardDesc: {
fontSize:15
},
cardDate: {
fontSize:10,
color:"#A6A6A6",
}
});
이렇게 국비지원 스파르타 코딩 앱개발 쌩초보 강의가 모두 마무리 되었습니다.
이제 다음 목표는 내 앱 출시하기! 강의 네대로 따라 들었으면 한개는 출시 했을텐데 이핑계 저핑계 대면서 조금 소홀했더니 출시까지는 못해봤네요. 1개월안에 1개 출시를 목표로 합니다.
'앱 개발' 카테고리의 다른 글
앱 개발 자바스크립트 쌩초보 4주차 공부내용 (0) | 2022.05.10 |
---|---|
앱 개발 자바스크립트 쌩초보 3주차 공부내용 (0) | 2022.05.04 |
앱 개발 자바스크립트 쌩초보 2주차 공부내용 (0) | 2022.04.26 |
앱 개발 자바스크립트 쌩초보 1주차 공부내용 (0) | 2022.04.20 |