# SDK: Flutter

{% hint style="info" %}
Native App Push の統合は現在クローズドベータ版です。ベータパートナーになる方法の詳細については、アカウントマネージャーにお問い合わせください。
{% endhint %}

## ステップ 1: PushSDK プラグインをインポートする

PushSDK プラグインをインストールする

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

```sh
flutter pub add pushly_pushsdk
```

{% endtab %}
{% endtabs %}

## ステップ2: Androidのセットアップ

### ステップ2.1: Gradle

必要な依存関係を追加して、gradleスクリプトを更新します:

{% tabs %}
{% tab title="android/build.gradle" %}

```gradle
buildscript {
    ...
    dependencies {
        ...
        classpath 'com.google.gms:google-services:4.3.13'
    }
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="android/app/build.gradle" %}

```gradle
android {
    compileSdk 33
    ...

    defaultConfig {
        ...
        targetSdk 33
    }
}

apply plugin: 'com.google.gms.google-services'
```

{% endtab %}
{% endtabs %}

### ステップ2.2: Google Services

次のファイルを追加します `google-services.json` ファイルを `android/app` ディレクトリに。

## ステップ3: iOSのセットアップ

### ステップ3.1: Podsをインストールする

次の場所で `<project_root>/ios` ディレクトリ内で以下を実行します: `pod install`

### ステップ3.2: Notification Service Extensionを追加する

画像やカスタムアクションをサポートするリッチ通知を有効にするには、Notification Service Extensionが必要です。

アプリの **xcworkspace** を使ってXCodeを開きます。次に、 `File > New > Target` を選択し、続いて `Notification Service Extension` をiOSテンプレートタブ内で選択して、 `Next`.

<figure><img src="https://1832353165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lry9Z27iWOZyQEGAgY7%2Fuploads%2FIKOtBgXyBx78VJBxuNs9%2Fimage.png?alt=media&#x26;token=b0055514-7e75-4ce8-a0b3-bbba8f2543c6" alt=""><figcaption></figcaption></figure>

"NotificationServiceExtension"を `Product Name` に入力し、アプリ拡張の他の設定詳細も入力してから、 `Finish` をクリックしますが、 **その後のダイアログでは有効化をクリックしないでください** 。

<figure><img src="https://1832353165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lry9Z27iWOZyQEGAgY7%2Fuploads%2F96yVKAthjykdmnXGXlem%2Fimage.png?alt=media&#x26;token=b8ed3424-44e0-4259-b97b-bb1457411164" alt=""><figcaption></figcaption></figure>

クリック `キャンセル` モーダルが閉じた後にデプロイメントターゲットを設定できるように、サービス拡張の有効化を求めるダイアログで

<img src="https://1832353165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lry9Z27iWOZyQEGAgY7%2Fuploads%2FcGXECnSyGjGGEUBg5KDM%2Fimage.png?alt=media&#x26;token=bc91b955-baa5-490f-a32b-dd7367657f9f" alt="" data-size="original">

デプロイメントターゲットを **メインのアプリケーションターゲットと同じ**に設定してください。特別な理由がない限り、 `Deployment Target` をiOS 11に設定するべきです。これはPushSDK Frameworkおよび最新のXCodeでサポートされるiOSの最低バージョンです。

### ステップ3.3: サービス拡張にPushly依存関係を追加する

次のファイルで `<project_root>/ios/Podfile`、 **NotificationServiceExtension** あなたの〜と同じ階層に **Runner** ターゲット:

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

```ruby
target 'NotificationServiceExtension' do
  use_frameworks!
  pod 'Pushly', '>= 1.0', '< 2.0'
end
```

{% endtab %}

{% tab title="Podfileの例" %}

```ruby
# グローバルなプラットフォームをプロジェクトに定義するには、この行のコメントを外してください
platform :ios, '11.0'

# CocoaPods の分析機能はネットワーク統計を同期的に送信し、flutter のビルド遅延に影響します。
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

target 'NotificationServiceExtension' do
  use_frameworks!
  pod 'Pushly', '>= 1.0', '< 2.0'
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end
```

{% endtab %}
{% endtabs %}

Podfileにサービス拡張の依存関係を追加したので、再度インストールを実行する必要があります。 `<project_root>/ios` ディレクトリ内で、以下を実行します: `pod install`.

### ステップ3.4: サービス拡張を更新する

次に、新しく作成されたNotification Service Extensionを開き、コードを以下の内容に置き換えます:

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

```swift
import Pushly

class NotificationService: PNNotificationServiceExtension {
}
```

{% endtab %}

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

```objectivec
// ヘッダーファイルのインポートは保持してください
#import "NotificationService.h"

@import Pushly;

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    [PNNotificationServiceExtensionHandler didReceiveExtensionRequest:request content:self.bestAttemptContent withContentHandler:contentHandler];
}

- (void)serviceExtensionTimeWillExpire {
    // 拡張機能がシステムによって終了される直前に呼び出されます。
    // 変更された内容の「最善の試行」を配信する機会として使用してください。そうしないと、元のプッシュペイロードが使用されます。
    [PNNotificationServiceExtensionHandler didRecieveExtensionTimeWillExpire:self.bestAttemptContent withContentHandler:self.contentHandler];

    self.contentHandler(self.bestAttemptContent);
}

@end
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Xcode が Pushly を見つけられないと警告する場合は、物理デバイス、またはビルド先として「Any iOS Device」が選択されていることを確認してください。
{% endhint %}

### ステップ3.4: メインアプリケーションターゲットに機能を追加する

{% hint style="warning" %}
Push Notifications機能は、 **メインのアプリケーションターゲット**.
{% endhint %}

のみに追加する必要があります。ルートプロジェクトを選択し、その後にメインのアプリケーションターゲット > `Signing & Capabilities`

<figure><img src="https://1832353165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lry9Z27iWOZyQEGAgY7%2Fuploads%2FPEKQiayxyjIphpjeqxB1%2Fimage.png?alt=media&#x26;token=84e69c08-d120-4a48-a193-a272b9e4f109" alt=""><figcaption></figcaption></figure>

次をクリックします `+ Capability` を選択して、 `Push Notifications`.

次をクリックします `+ Capability` を選択して、 `Background Modes`.

を追加します。 `Background Modes` 機能を追加した後、 `Remote Notifications` が有効になっていることを確認してください。

<figure><img src="https://1832353165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lry9Z27iWOZyQEGAgY7%2Fuploads%2FMAfJ7lisFKGMxQvjpIaB%2Fimage.png?alt=media&#x26;token=7b5b4afb-0a24-4b0a-8ef6-594f763231ea" alt=""><figcaption></figcaption></figure>

次をクリックします `+ Capability` を選択して、 `App Groups`.

次をクリックします `+` 内にある `App Groups` セクションのシンボルを使って新しい名前付きコンテナーを追加します。PushSDKが情報を正しく取得できるようにするには、コンテナー名を `group.{app-bundle-id}.push`.

<figure><img src="https://1832353165-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lry9Z27iWOZyQEGAgY7%2Fuploads%2FOR42sYi1kH4o1227pQpY%2Fimage.png?alt=media&#x26;token=c504305e-c703-4e7e-afff-834d9de68aac" alt=""><figcaption></figcaption></figure>

にする必要があります。メインのアプリケーションターゲットで、新しく作成したApp Groupの横のチェックボックスをオンにします。

### ステップ3.5: Notification Service Extensionに機能を追加する

次に、 **NotificationServiceExtension** ターゲットで `Signing & Capabilities` タブの下に表示されます。

次をクリックします `+ Capability` を選択して、 `App Groups`.

最後に、新しく作成したApp Groupの横のチェックボックスをオンにします。

## ステップ4: SDKの初期化

次のファイルで `main.dart` ファイルで、以下のサンプル実装コードを使ってPushSDKを初期化します。

次の `REPLACE_WITH_SDK_KEY` を `setConfiguration` メソッド内で、プラットフォーム設定ページのSDKキーに置き換えてください。

{% tabs %}
{% tab title="main.dart" %}

```dart
...
import 'package:pushly_pushsdk/pushsdk.dart';

...
// アプリの初期化関数内で
await PushSDK.setLogLevel(PNLogLevel.info);
await PushSDK.setConfiguration('REPLACE_WITH_SDK_KEY');

await PushSDK.showNativeNotificationPermissionPrompt(completion: ( granted, status, error ) {
    print('権限が付与されました: $granted');
});
```

{% endtab %}
{% endtabs %}

Androidデバイスまたはエミュレーター（エミュレーターに `Google Play ストア サービス` がインストールされていることを確認してください）、またはiOS向けにビルドする場合はiOSデバイスでアプリを実行し、正しくビルドされることを確認してください。

前のステップで追加したコードにより、アプリ起動時にプッシュ権限ダイアログが表示されます。これは [<mark style="color:青色;">SDK メソッド</mark>](https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/sdk-flutter/sdkmesoddo) を使用して、ダイアログを表示するタイミングを制御することでカスタマイズできます。

ダイアログを承認した後、プラットフォームにログインして `Notifications > Create Notification` に移動し、適切な **ネイティブ: iOS** または **ネイティブ: Android** チャネル

## 次のステップ

SDK が正しく動作していることを確認したら、次のような追加のオプション機能を引き続き追加できます:

* [<mark style="color:青色;">通知の開封 / アプリリンク / ディープリンクの処理</mark>](https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/sdk-flutter/dpurinku)
* [<mark style="color:青色;">購読者のプロフィールに属性を付与する</mark>](https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/sdkmesoddo#adding-attributes-to-a-subscribers-profile)
* [<mark style="color:青色;">購読者がどのコンテンツとやり取りしたかに関する情報を送信する</mark>](https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/akutibititorakkingu#userprofile.trackactivity)
