O'Reilly의 책을 참고하고 있으므로 아래 샘플앱 코드를 참고

https://github.com/bonniee/learning-react-native

 

본 내용은 가능한 윈도우 기반으로 설명토록 하겠습니다.

 

윈도우 커맨드를 통해 WeatherProject 생성

react-native init WeatherProject

 

WeatherProject폴더 밑에 index.android.js 생성

* iOS를 사용한다면 index.ios.js 생성

import { AppRegistry } from 'react-native'

import WeatherProject from './WeatherProject_Part1'; //class import

AppRegistry.registerComponent('WeatherProject', () => WeatherProject);

 

깃허브의 src/Weather에서 WeatherProject_Part1.js 파일을 로컬 WeatherProject로 다운로드

 

# WeatherProject_Part1 간략 코드 설명

  constructor(props) {
    super(props);
    this.state = { zip: "" };
  }

//render 함수 이전에 zip 변수 초기화

 

_handleTextChange = event => {
    this.setState({ zip: event.nativeEvent.text });
  };

//Text change event의 결과를 zip 변수에 저장

 

render() {

style={styles.input}

onSubmitEditing={this._handleTextChange}

// render()내 onSubmitEditing에 _handleTextChange을 연결

}

const styles = StyleSheet.create({
  container: { .. }

})

// render내 스타일 속성 정의

 

WeatherProject내에서 react-native WeatherProject 실행

 

 

zip code를 입력받아 날씨 정보를 서버로부터 받아 보여주는 코드를 추가해본다.

 

깃허브의 src/Weather에서 Weather.js, Forecast.js, open_weather_map.js, flowers.png 파일을 로컬 WeatherProject로 다운로드

* index.android.js의 import WeatherProject from './WeatherProject_Part1';를 './Weather';로 수정

 

iOS image file 추가 : Images.xcassets/ 폴더 선택 -> New Image Set

* Image Set은 파일 이름과 동일 하게 설정

 

안드로이드 image file 추가 : WeatherProject/android/app/src/main/res의 모든 하위폴더에 이미지 파일 추가

 

# Weather.js 코드 설명

 

import React, { Component } from "react";
import { StyleSheet, Text, View, TextInput, ImageBackground } from "react-native";

//Image가 패치되어 ImageBackground를 사용
import Forecast from "./Forecast"; 

//날씨 정보의 결과를 저장하는 객체
import OpenWeatherMap from "./open_weather_map";

//서버에서 날씨정보를 받아오는 모듈

 

_handleTextChange = event => {
    let zip = event.nativeEvent.text;
    OpenWeatherMap.fetchForecast(zip).then(forecast => {
      this.setState({ forecast: forecast });
    });
  };

//zip code를 입력받으면 zip 변수에 저장하고 날씨 정보를 받아 forecast 형태로 저장

 

render() {
    let content = null;
    if (this.state.forecast !== null) {
      content = (
                  main={this.state.forecast.main}
          description={this.state.forecast.description}
          temp={this.state.forecast.temp}
        />
      );
    }
    ...

} //forecast 객체가 채워지면 content에 담는다.

 

나머지 render 코드 내용은 아래와 같다.

- Image component가 하위 component를 가질 수 없도록 패치가 되어 ImageBackground를 사용

- 레퍼런스 코드의 TextInput의 속성에 대한 결과가 예상과 달라 아래와 같이 StyleSheet 수정

* Style 속성 값 추후 수정 필요

 

 

결과 화면

 

'React native' 카테고리의 다른 글

Todo 1  (0) 2019.12.25
State, Props, Lifecycle  (0) 2019.12.25
Project 생성 및 빌드  (0) 2019.12.25
React native intro  (0) 2019.12.25
React native 설치  (0) 2019.04.14

O'Reilly의 책을 보며 기본 환경 설정을 해봤는데 맥 기준이라(iOS는 책 따라하면 잘 됨) 윈도우 기반 환경 설정에 대한 검색이 따로 필요 할 수 있다.(Hello world는 언제나 중요하다.)

 

React native의 개발은 expo와 react-native 두 가지 방식이 있다.(npm 패키지)

* 처음에 두개가 같은 건 줄 알고 검색을 통해 윈도우에 expo를 설치하곤 책을 따라 가다가 아차 싶었음..

 

react-native : iOS, Android base코드가 함께 있어 단말이나 에뮬레이터를 통해 컴파일을 거쳐 결과를 확인

expo : 개발 PC에 node 서버를 작동시켜 프로젝트를 활성화 시키고 단말의 expo앱을 통해 접속하여 결과 확인하는 방식(PC와 단말이 같은 네트워크에 묶여 있어야 함)

 

위 책을 통해 공부를 하실 분들은 react-native를 쓰시면 될 것 같다. 

*공통적으로 JDK는 필요

 

#맥(react-native 책 방식 수정)

0.homebrew 설치 

https://brew.sh/index_ko

 

1. node, watchman, flow 설치

brew install node

brew install watchman

brew install flow

 

2. react command-line 설치

npm install -g react-native-cli

 

3-1. iOS개발자 계정, xcode 설치

3-2. 안드로이드 Studio 설치

https://developer.android.com/studio

android studio 실행 후 SDK 매니저 실행 (SDK Build-tools, API, Support Repository, Intel x86 패키지 설치)

* Sutdio, SDK 설치 후 SDK 경로를 ANDROID_HOME으로 환경변수 추가(~/.bash_profile)

 

4. 프로젝트 생성 : react-native init test-app

 

5-1. 아이폰에서 프로젝트 실행

iOS폴더 xcode에서 열고 run

* 실패 시 test-app폴더에서 npm install, npm start 실행

* iOS packager가 실행 되고 실제 단말에서 테스트하기 위해서는 단말등록, 앱 배포 인증 필요... 

 

5-2. 안드로이드에서 프로젝트 실행

android studio를 통해 테스트 할 avd 생성 후 실행 or 단말 연결

test-app 폴더에서 react-native run-android

* 가끔 .. Device is UNAUTHORIZED를 포함한 에러를 일으키는데 adb server restart를 통해 

adb server를 재시작 하여 단말 연결을 다시 해본다. (emulator -list-avds 로 연결 단말 확인)

 

 

#윈도우(react-native android only)

1. node.js 설치

 

2. react command-line 설치

npm install -g react-native-cli

 

3. 프로젝트 생성 : react-native init test-app

 

4. 안드로이드 스튜디오, SDK 설치 

android studio 실행 후 SDK 매니저 실행 (SDK Build-tools, API, Support Repository, Intel x86 패키지 설치)

 

5. 안드로이드의 device manager 실행, 테스트 단말 생성, 실행 or 테스트 단말 연결

 

6. 윈도우 커맨드 실행하여 test-app이동 후 react-native run-android 실행

 

* 윈도우 시스템 환경변수에 JAVA_HOME 추가 필요 (같은 식으로 ANDROID_HOME도 추가)

 

* 그 외 run-android가 안되는 경우 위 맥의 5-2를 참고(안드로이드 스튜디오에서 테스트 단말이 제대로 연결 되었는지 확인 필요)

 

#expo 방식

1. node.js 설치

2. npm을 통한 express(expo포함) 설치

npm install express 
npm init -y

* package.json의 version 수정 (6.4.1)

3. react native 프로젝트 생성

expo init test-app

 -> blank, tab 스타일 선택, 타이틀 이름 설정 후 엔터

4. 프로젝트 실행

cd test-app

npm start

5. 핸드폰에 expo 앱 설치

6. expo앱으로 4의 QR코드 스캔 (같은 네트워크에 개발 단말, 데스크탑 연결)

'React native' 카테고리의 다른 글

Todo 1  (0) 2019.12.25
State, Props, Lifecycle  (0) 2019.12.25
Project 생성 및 빌드  (0) 2019.12.25
React native intro  (0) 2019.12.25
첫 애플리케이션 만들기  (0) 2019.04.14

Firebase란 쉽게 클라이언트 개발자가 직접 서버를 만들필요 없도록 상용화 서버 플렛폼을 제공하는 서비스입니다. 


node.js 등으로 직접 서버를 개발하여 클라이언트의 데이터를 백업하거나 서버기반 클라이언트를 개발 할 수 있으나 특별한 기능을 요하지 않는 서버라면


Firebase로 충분히 커버가 가능합니다. 기본적으로 인증(구글 로그인 등) 그 외 사용자 로그, 분석, 서버DB, 저장소.. 기본적인 기능은 너무나 잘 구성되어 있


을뿐더러 초기 배포선에서 '무료'로 사용할 수 있다는 점이 매력적입니다. 




https://firebase.google.com/docs/android/setup?authuser=0


잘 정리되어 있는 공식 가이드를 참고합니다. 



1. 프로젝트 레벨의 build.gradle에 아래 내용을 추가합니다. 

buildscript {
   
// ...
    dependencies
{
       
// ...
        classpath
'com.google.gms:google-services:4.2.0' // google-services plugin
   
}
}


2. 앱 레벨의 build.gradle에 아래 내용을 추가합니다. 

dependencies {
 
// ...
  implementation
'com.google.firebase:firebase-core:16.0.6'

 
// Getting a "Could not find" error? Make sure you have
 
// added the Google maven respository to your root build.gradle
}

// ADD THIS AT THE BOTTOM
apply plugin
: 'com.google.gms.google-services'


3. build.gradle 오른쪽 구석에 sync버튼을 눌러 추가한 라이브러리를 다운로드 받습니다. 



개발중인 앱에 기본 Firebase SDK를 추가하였습니다. 


그럼 Firebase에 개발중인 앱을 등록하겠습니다. 


https://console.firebase.google.com/


1. Firebase 콘솔로 이동하여 '프로젝트 추가'를 합니다. 


프로젝트 이름 등 필요한 정보를 입력합니다.(패키지 이름은 개발중인 앱의 AndroidManifest.xml 에서 가져옵니다.)


google-service.json 파일을 개발중인 앱의 app폴더 아래에 넣습니다. 


SHA 인증서 지문까지 입력하고 완료합니다.(SHA는 선택적인데 입력하지 않으면 google로그인 등 인증 기능을 사용할 수 없습니다.)

* SHA 개발중인 프로젝트 마다 고유의 Signing key가 존재합니다. 


2. 생성된 프로젝트를 눌러보면 Firebase에서 지원하는 기능들이 나열된 메뉴와 현황판이 있습니다. 


앞으로 인증, Analytics등 개발중인 프로젝트에 기능을 추가하면 해당 콘솔에서 클라이언트에서 서버로 전송된 기록을 확인할 수 있습니다. 





'Android' 카테고리의 다른 글

Floating Action Button  (0) 2021.03.29
Parcelable  (0) 2021.03.24
안드로이드 Application class  (0) 2019.03.05
안드로이드 앱 개발의 기본 아키텍쳐  (0) 2019.03.01

+ Recent posts