# React Native

React Native 앱에 애드체인 SDK를 연동하는 방법을 소개합니다.

## 시작하기 전에

SDK를 설치하기 전에 다음을 준비해주세요:

* **React Native**: 0.74 이상
* **iOS**: 14.0 이상
* **Android**: SDK 24 (Android 7.0) 이상
* **Node.js**: 16 이상
* **appKey & appSecret**: 애드체인 ADMIN에서 발급받은 인증 정보 (<contact@1self.world>로 문의)

Expo 프로젝트에서도 쓸 수 있습니다. SDK가 자동으로 Expo 환경을 감지합니다.

## 1. SDK 설치

### npm으로 설치

```bash
npm install @1selfworld/adchain-sdk-core-react-native
```

또는 yarn을 쓴다면:

```bash
yarn add @1selfworld/adchain-sdk-core-react-native
```

### iOS 의존성 설치

iOS는 CocoaPods로 네이티브 라이브러리를 설치해야 합니다:

```bash
cd ios
pod install
cd ..
```

### Android 추가 설정 (필수)

React Native는 네이티브 모듈을 사용하므로, **Android 프로젝트에 JitPack Maven 저장소를 추가해야 합니다**.

`android/build.gradle` 파일을 열어서 다음 내용을 추가하세요:

```groovy
allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://www.jitpack.io' }
        // 기존 저장소들...
    }
}
```

**또는**, 프로젝트가 `settings.gradle`을 사용한다면:

```groovy
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://www.jitpack.io' }
    }
}
```

## 2. 네이티브 설정

### Android 매니페스트 설정

`android/app/src/main/AndroidManifest.xml` 파일을 열어서:

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 필수 권한 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 광고 ID 권한 (필수) -->
    <uses-permission android:name="com.google.android.gms.permission.AD_ID" />

    <application>
        <!-- 기존 내용... -->

        <!-- 오퍼월 Activity 추가 -->
        <activity
            android:name="com.adchain.sdk.offerwall.AdchainOfferwallActivity"
            android:configChanges="orientation|screenSize|keyboardHidden"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
    </application>
</manifest>
```

### iOS 설정

`ios/YourApp/Info.plist` 파일에:

```xml
<!-- HTTP 통신 허용 -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

<!-- 광고 추적 권한 문구 -->
<key>NSUserTrackingUsageDescription</key>
<string>맞춤형 광고를 제공하기 위해 사용됩니다</string>
```

## 3. SDK 초기화

`App.tsx` 또는 메인 컴포넌트에서 SDK를 초기화합니다:

```typescript
import React, { useEffect } from 'react';
import { AdchainSdk } from '@1selfworld/adchain-sdk-core-react-native';

function App() {
  useEffect(() => {
    initializeSDK();
  }, []);

  const initializeSDK = async () => {
    try {
      await AdchainSdk.initialize({
        appKey: 'YOUR_APP_KEY',
        appSecret: 'YOUR_APP_SECRET',
        environment: 'PRODUCTION',  // 또는 'STAGING'
      });
      console.log('SDK 초기화 성공');
    } catch (error) {
      console.error('SDK 초기화 실패:', error);
    }
  };

  return (
    // 앱 UI...
  );
}

export default App;
```

environment는 개발 중에는 `'STAGING'`으로, 릴리스할 때는 `'PRODUCTION'`으로 바꿔주세요.

## 4. 사용자 로그인

SDK를 쓰려면 사용자 로그인이 필요합니다:

```typescript
import { AdchainSdk } from '@1selfworld/adchain-sdk-core-react-native';

const loginUser = async () => {
  try {
    await AdchainSdk.login({
      userId: 'user123',       // 앱의 사용자 ID (필수)
      gender: 'MALE',          // 'MALE', 'FEMALE', 'OTHER', 'M', 'F' (선택)
      birthYear: 1990,         // 출생연도 (선택)
    });
    console.log('로그인 성공');
  } catch (error) {
    console.error('로그인 실패:', error);
  }
};
```

일반적으로 앱의 로그인 화면에서 처리합니다.

## 5. 오퍼월 띄우기

### 전체 화면 오퍼월

버튼을 누르면 오퍼월이 열리도록:

```typescript
import React from 'react';
import { Button, Alert } from 'react-native';
import { AdchainSdk } from '@1selfworld/adchain-sdk-core-react-native';

function HomeScreen() {
  const openOfferwall = async () => {
    try {
      await AdchainSdk.openOfferwall('main_offerwall');
    } catch (error) {
      Alert.alert('오류', '오퍼월을 열 수 없습니다');
    }
  };

  return (
    <Button title="오퍼월 열기" onPress={openOfferwall} />
  );
}
```

### 임베디드 오퍼월 (화면 일부에 넣기)

화면의 특정 영역에 오퍼월을 넣고 싶다면:

```typescript
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { AdchainOfferwallView } from '@1selfworld/adchain-sdk-core-react-native';

function BenefitsScreen() {
  return (
    <View style={styles.container}>
      <AdchainOfferwallView
        style={styles.offerwallView}
        placementId="benefits_tab"
        onOfferwallOpened={() => console.log('오퍼월 로드됨')}
        onOfferwallError={(error: string) => console.error('오퍼월 에러:', error)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  offerwallView: {
    flex: 1,
    width: '100%',
  },
});
```

이렇게 하면 탭이나 화면 일부에 오퍼월을 계속 띄워둘 수 있습니다.

## iOS ATT 권한 요청

iOS에서 광고 추적 권한을 요청하려면 별도로 처리해야 합니다:

```typescript
import { Platform } from 'react-native';
import { requestTrackingPermissionsAsync } from 'expo-tracking-transparency';  // Expo인 경우

const requestATT = async () => {
  if (Platform.OS === 'ios') {
    try {
      const { status } = await requestTrackingPermissionsAsync();
      if (status === 'granted') {
        console.log('추적 허용됨');
      }
    } catch (error) {
      console.error('ATT 권한 요청 실패:', error);
    }
  }
};
```

Expo가 아니라면 `react-native-tracking-transparency` 같은 라이브러리를 쓰시면 됩니다.

## 로그아웃

사용자가 로그아웃할 때:

```typescript
await AdchainSdk.logout();
```

## 다음 단계

기본 설정이 끝났습니다. 이제 다른 기능들을 써볼 수 있습니다:

* [오퍼월 상세 사용법](/undefined-2/offerwall.md)
* [퀴즈 사용하기](/undefined-2/quiz.md)
* [미션 사용하기](/undefined-2/mission.md)

## 문제가 생겼다면

* Android에서 빌드 에러가 나면: `cd android && ./gradlew clean` 후 다시 빌드
* iOS에서 빌드 에러가 나면: `cd ios && pod deintegrate && pod install` 후 다시 빌드
* 그 외 문제는 [문제 해결](/undefined-6/common-issues.md) 페이지 참고

## Expo 프로젝트 주의사항

Expo Go 앱에서는 네이티브 모듈을 쓸 수 없어서 SDK가 작동하지 않습니다. Development Build를 만들어서 테스트해야 합니다:

```bash
eas build --profile development --platform ios
eas build --profile development --platform android
```

## TypeScript

SDK는 TypeScript 타입 정의를 포함하고 있어서, VSCode에서 자동완성이 잘 됩니다. 따로 @types 패키지를 설치할 필요 없습니다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://adchain-doc.1self.world/undefined/react-native.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
