앱개발 종합반 4주차

귀찮Lee·2022년 3월 23일
0

App 강의

목록 보기
4/9

□ [왕초보] 나만의 수익성 앱, 앱개발 종합반 (4주차 과정)

22.03.22(화) ~ 23(수)

◎ 외부 API 이용하기

  • 서버가 제공하는 도메인 사용하여 데이터 가져오기
    (openweathermap API 사용해보기)
  • 현재 위치(좌표) 데이터 필요, 가져오기
// 설치하기
expo install expo-location

----------------------------
import * as Location from "expo-location";

try {
      await Location.requestPermissionsAsync();
      const locationData= await Location.getCurrentPositionAsync();
			console.log(locationData)
    } catch (error) {
      //혹시나 위치를 못가져올 경우를 대비해서, 안내를 준비합니다
      Alert.alert("위치를 찾을 수가 없습니다.", "앱을 껐다 켜볼까요?");
    }
  • 외부 API 사용하기 위해 axios 사용
// 설치하기
yarn add axios

-------------------------------
import axios from "axios"
 const getLocation = async () => {
    //수많은 로직중에 에러가 발생하면
    //해당 에러를 포착하여 로직을 멈추고,에러를 해결하기 위한 catch 영역 로직이 실행
    try {
      //자바스크립트 함수의 실행순서를 고정하기 위해 쓰는 async,await
      await Location.requestPermissionsAsync();
      const locationData= await Location.getCurrentPositionAsync();
      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`
      );

파이어베이스(firebase)

  • 서버리스(serverless) : 여러분들은 서버를 직접 구현, 구성 할 필요없이 필요한 서버 기능을 제공하는 곳에서, 서비스를 사용하기만 하면 된다.

  • 파일 저장소 스토리지(storage) : 특정 사진/데이터를 링크를 통해 얻오올 수 있게 함 // 주로 이미지 저장에 이용

  • 리얼타임 데이터베이스: 우리가 배운 리스트, 딕셔너리 구조, 즉 JSON 형태로 저장/관리되는 데이터베이스 서비스 이다. 파이어베이스에서 제공해주는 함수들을 이용하기만 하면 데이터 저장/수정/삭제가 가능함. // 주로 json 데이터 저장에 이용

◎ 파이어베이스(firebase) 앱과 연결

// 설치하기
expo install firebase

// 기본 연결 데이터를 저장할 firebaseConfig.js 생성
  
//import * as firebase from 'firebase/app';
import firebase from 'firebase/app';

// 사용할 파이어베이스 서비스 주석을 해제합니다
//import "firebase/auth";
import "firebase/database";
//import "firebase/firestore";
//import "firebase/functions";
import "firebase/storage";

// Initialize Firebase
//파이어베이스 사이트에서 봤던 연결정보를 여기에 가져옵니다
const firebaseConfig = {
  apiKey: "AIzaSyBKG2xY91x23W8PF1231k5OUJ5o9kHSKYQeNWUw",
  authDomain: "sparta-psytest-gun.firebaseapp.com",
  databaseURL: "https://sparta-psytest-gun.firebaseio.com",
  projectId: "sparta-psytest-gun",
  storageBucket: "sparta-psytest-gun.appspot.com",
  messagingSenderId: "781790378482",
  appId: "1:78179037128482:web:ddbca5330779f67b947136b",
  measurementId: "G-3F5L9F3340Q3"
};

//사용 방법입니다. 
//파이어베이스 연결에 혹시 오류가 있을 경우를 대비한 코드로 알아두면 됩니다.
if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
}

export const firebase_db = firebase.database()

◎ 리얼타임 데이터베이스 특정 데이터 읽기, 쓰기

import {firebase_db} from "../firebaseConfig"

// 데이터 읽어오기
firebase_db.ref('/tip/'+idx).once('value').then((snapshot) => {
            let tip = snapshot.val();})

// 데이터 저장하기
firebase_db.ref('/like/'+user_id+'/'+ tip.idx).set(tip,function(error){
            console.log(error)
            Alert.alert("찜 완료!")
        });

// 데이터 삭제하기
firebase_db.ref('/like/'+user_id+'/'+content.idx).remove().then(function(){
            Alert.alert("삭제 완료");
            reload()}
  • ref: 파이어베이스 안에서 폴더 구조
  • set: 해당 내용 저장
  • remove 해당 내용 삭제
profile
배운 것은 기록하자! / 오류 지적은 언제나 환영!

0개의 댓글