# 연동하기

이 문서는 Adbrix React Native SDK를 앱에 통합하는 방법을 다룹니다. Adbrix SDK를 설치하면 이벤트 분석 기능이 제공됩니다.

더 자세히 알아보려면 [리소스 및 샘플](https://adbrix.gitbook.io/developer-guide/common/resource-and-sample)을 참조하세요.

## 시작하기 전에

### 앱 생성

[Adbrix 콘솔](https://console.adbrix.ai/)의 `앱 설정/앱 정보` 페이지에서 앱을 생성하여 SDK 초기화에 필요한 **Application Key**와 **Secret Key**를 발급받아 주십시오.

![앱 정보](https://3478783164-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FnJIV3KSW5duLCA7m693B%2Fuploads%2Fgit-blob-6228fd98bac706c18facda8b3b9116f69ff3f57d%2Fappinfo.png?alt=media)

### 지원 정보

#### Android

* 최소 지원 SDK : Android 4.4+ / API 19+
* Compile SDK : 35

#### iOS

* iOS 12.0
* Xcode 16.0

### 의존성

#### Android

* [com.android.installreferrer:installreferrer:2.2](https://mvnrepository.com/artifact/com.android.installreferrer/installreferrer)
* [com.google.android.gms:play-services-ads-identifier:18.2.0](https://mvnrepository.com/artifact/com.google.android.gms/play-services-ads-identifier)

## SDK 설치

### 터미널에서 Adbrix 패키지를 추가합니다.

다음의 명령어를 입력하여 프로젝트에 Adbrix React Native SDK 패키지를 추가하세요.

{% tabs %}
{% tab title="NPM" %}

```
npm install @igaworks/adbrix-react-native-sdk
```

{% endtab %}

{% tab title="YARN" %}

```
yarn add @igaworks/adbrix-react-native-sdk
```

{% endtab %}
{% endtabs %}

### SDK 설정하기

{% tabs %}
{% tab title="Android" %}
**`AndroidManifest.xml` 설정하기**

**1. `<manifest>` 내에 다음의 권한을 추가해주세요.**

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID" /><!-- 구글 광고 ID를 수집해야할 경우 추가합니다. -->
```

**2. 설정이 완료되었습니다.**

다음은 작성이 완료된 예시입니다.

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.gms.permission.AD_ID" /><!-- 구글 광고 ID를 수집해야할 경우 추가합니다. -->
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      android:supportsRtl="true">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    </application>
</manifest>

```

{% endtab %}
{% endtabs %}

## SDK 초기화

### 초기화 하기

앱에서 Adbrix SDK를 초기화하려면 다음 단계를 완료하세요.

#### 1. 스크립트에 Adbrix를 추가합니다.

```typescript
import Adbrix from '@igaworks/adbrix-react-native-sdk';
```

#### 2. `useEffect()` 내에 다음 코드를 작성합니다.

{% hint style="info" %}
Application KEY와 SECRET KEY는 [Adbrix Console](https://console.adbrix.ai/)의 `앱 설정 > 앱 정보`에서 확인이 가능합니다.
{% endhint %}

```typescript
import React, { useEffect } from "react";
import Adbrix from '@igaworks/adbrix-react-native-sdk';

const App = () => {
  useEffect(() => {
    Adbrix.init({
      applicationKey: "{YOUR_APPLICATION_KEY}", 
      secretKey: "{YOUR_SECRET_KEY}"
      });
  }, []);

  return (
    <div>
      ...
    </div>
  )
```

#### 3. 초기화가 완료되었습니다.

### 구글 광고 ID 설정하기 <a href="#set_collect_google_advertising_id" id="set_collect_google_advertising_id"></a>

Google 광고 ID를 수집하기 위해선 Config의 `ANDROID_COLLECT_GOOGLE_ADVERTISING_ID`를 **true**로 설정하여 수집 여부를 설정해야합니다. 만약 Google 광고ID를 수집하지 않아야 한다면, [구글 광고 ID 수집 여부 변경하기](#change_collect_google_advertising_id)를 통해 수집하지 않도록 설정할 수 있습니다.

```typescript
const config = {
  [ABConfig.ANDROID_COLLECT_GOOGLE_ADVERTISING_ID]: true
};
Adbrix.initWithConfig({
    applicationKey: "{YOUR_APPLICATION_KEY}", 
    secretKey: "{YOUR_SECRET_KEY}",
    config: config
});
```

## 딥링크 오픈 분석

#### Android

딥링크 정보를 가지고 있는 트래킹링크를 클릭하면 딥링크에 설정된 [Activity](https://developer.android.com/reference/android/app/Activity)가 실행됩니다. 딥링크가 정보가 없을 경우 `android.intent.action.MAIN` 액션을 가지고 있는 Activity가 실행됩니다.

{% hint style="info" %}
Activity에 딥링크를 연동하는 방법은 Android에서 제공하는 [앱 콘텐츠 딥링크 만들기](https://developer.android.com/training/app-links/deep-linking?hl=ko)를 참고하여 주시기 바랍니다.
{% endhint %}

#### iOS

iOS에서는 [딥링크(Custom URL Schemes)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)와 [유니버셜 링크(Universal Links)](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app)를 통해 앱을 열 수 있습니다. Adbrix SDK는 이러한 링크를 통한 앱 오픈을 분석합니다.

### 딥링크 연동하기

#### Android

딥링크 추적을 위해 딥링크로 인해 실행 될 Activity에 `setIntent()`를 추가해주시기 바랍니다.

{% tabs %}
{% tab title="Java" %}

```java
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent); 
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    setIntent(intent)
}
```

{% endtab %}
{% endtabs %}

#### iOS

딥링크 추적을 위해 AppDelegate에 다음 코드를 추가해주시기 바랍니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import adbrix_react_native_sdk
  
  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    
    AdbrixReactNative.deepLinkOpen(url: url)
    ...
    ...
  }
  
  func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([any UIUserActivityRestoring]?) -> Void) -> Bool {
    
    AdbrixReactNative.deepLinkOpen(userActivity: userActivity)
    ...
    ...
  }
```

{% endtab %}

{% tab title="Objective-C" %}

```objc
#import <adbrix-react-native-sdk/AdbrixReactNativeSdk.h>


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  [AdbrixReactNativeSdk deeplinkOpenWith:url];
  ...
  ...
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
  [AdbrixReactNativeSdk deeplinkOpenWithUserActivity:userActivity];
  ...
  ...
}

```

{% endtab %}
{% endtabs %}

### 지연된 딥링크 핸들링하기(선택사항)

SDK는 앱이 설치되지 않은 유저가 트랙킹 링크를 클릭 후 앱을 설치했을때 자동으로 딥링크를 실행합니다. 직접 지연된 딥링크를 핸들링 하려면 다음 메소드를 호출하여 자동 딥링크 실행을 막을 수 있습니다.

```typescript
static blockDeferredDeepLinkLaunch(): Promise<AdbrixDeepLinkCallback | null>;
```

{% hint style="warning" %}
해당 메소드를 호출할 경우 지연된 딥링크의 경로로 Activity를 실행하지 않으므로 필요할 경우 직접 이동시켜야합니다.
{% endhint %}

```typescript
Adbrix.blockDeferredDeepLinkLaunch().then((value)=>{
  if(value != null){
    const deepLink = value.deepLink;
  }
});
```

#### AdbrixDeepLinkCallback

**result: number**

지연된 딥링크 처리 결과 입니다. ABDeepLinkResult 클래스로 해당 결과 값의 의미를 파악할수있습니다.

```typescript
const result = value.result;
```

* 결과 값 의미
  * 0 : `PROCESSED`
  * 1 : `ORGANIC`
  * 2 : `TRACKING_LINK_SETTINGS_INCORRECTLY`
  * 3 : `ORGANIC_NCPI_IN_PROCESS`
  * -1 : `NO_CONVERSION`

**deepLink : string**

지연된 딥링크 값입니다.

```typescript
const deepLink = value.deepLink;
```

## SDK 설정

SDK 초기화 시에 로그 활성화 등의 옵션을 설정할 수 있습니다.

### 로그 활성화 하기

플랫폼에 따라 `ABConfig.IOS_LOG_ENABLE` 혹은 `ABConfig.ANDROID_LOG_ENABLE`를 사용합니다.

```typescript
const config = {
  [ABConfig.IOS_LOG_ENABLE]: true,
  [ABConfig.ANDROID_LOG_ENABLE]: true,
};
Adbrix.initWithConfig({
    applicationKey: "{YOUR_APPLICATION_KEY}", 
    secretKey: "{YOUR_SECRET_KEY}",
    config: config
});
```

### 로그 레벨 변경하기

`ABConfig.ANDROID_LOG_LEVEL`를 사용하여 로그 레벨 설정을 변경할 수 있습니다.

{% hint style="info" %}
로그 레벨 값은 [`android.util.Log`](https://developer.android.com/reference/android/util/Log#constants_1)의 상수 값의 정의를 따릅니다.
{% endhint %}

```typescript
const config = {
  [ABConfig.ANDROID_LOG_LEVEL]: ABAndroidLogLevel.VERBOSE,
};
Adbrix.initWithConfig({
    applicationKey: "{YOUR_APPLICATION_KEY}", 
    secretKey: "{YOUR_SECRET_KEY}",
    config: config
});
```

* ABAndroidLogLevel
  * VERBOSE : `2`
  * DEBUG : `3`
  * INFO : `4`
  * WARN : `5`
  * WARN : `6`
  * ASSERT : `7`

### 구글 광고 ID 수집 여부 변경하기 <a href="#change_collect_google_advertising_id" id="change_collect_google_advertising_id"></a>

`ABConfig.ANDROID_COLLECT_GOOGLE_ADVERTISING_ID`를 사용하여 Android 플랫폼에서 구글 광고 ID의 수집 여부를 변경할 수 있습니다.

{% hint style="warning" %}
구글 광고 ID를 수집하려면 [play-services-ads-identifier](https://mvnrepository.com/artifact/com.google.android.gms/play-services-ads-identifier) 의존성 추가가 필요합니다. [여기](#set_collect_google_advertising_id)를 참고하세요.
{% endhint %}

```typescript
const config = {
  [ABConfig.ANDROID_COLLECT_GOOGLE_ADVERTISING_ID]: true
};
Adbrix.initWithConfig({
    applicationKey: "{YOUR_APPLICATION_KEY}", 
    secretKey: "{YOUR_SECRET_KEY}",
    config: config
});
```

### App Tracking Transparency (ATT) 지원

idfa 수집 가능 시점부터 SDK 이벤트를 수집하고 싶다면 다음 설정을 추가해주세요.

{% hint style="warning" %}
해당 설정 적용 시, 적용한 시간(초) 만큼, ATTAuthorized 메소드가 호출되기 전까지 SDK 이벤트 수집이 지연됩니다.
{% endhint %}

```typescript
const config = {
  [ABConfig.IOS_TRACKING_TIMEOUT]: ABiOSTrackingTimeout.TIMEOUT_60
};
Adbrix.initWithConfig({
    applicationKey: "{YOUR_APPLICATION_KEY}", 
    secretKey: "{YOUR_SECRET_KEY}",
    config: config
});
```

`Adbrix.attAuthorized(authorized: boolean)` 메소드를 추적 허용 여부가 판단되는 시점에 호출해주세요.

다음은 [react-native-permissions](https://github.com/zoontek/react-native-permissions) 패키지를 활용한 App Tracking Transparency (ATT) 구현 예시입니다.

```typescript
request(PERMISSIONS.IOS.APP_TRACKING_TRANSPARENCY)
  .then((result) => {
    if (result === RESULTS.GRANTED) {
      Adbrix.attAuthorized(true);
    } else {
      Adbrix.attAuthorized(false);
    }
  })
```

## 완료

SDK 설치 및 초기화가 완료되었습니다.
