# SDK: Swift / Obj-C

## 前提条件

SDKをアプリに統合する前に、以下の要件を満たしている必要があります：

* 開発およびテスト用の iOS 11+ デバイス（iPhone、iPad、または iPod Touch）。
  * **注：** XCode シミュレーターはリモートプッシュ通知をサポートしていません。物理デバイスを使用する必要があります。
* XCode 14+（Swift を使用する場合は Swift 5.7）がインストールされた Mac OS デバイス。
* iOS の P12 プッシュ証明書または P8 キー。これらをまだお持ちでない場合は、 [<mark style="color:青色;">こちらのドキュメント</mark>](/pushly-ja/integration/implementation-steps/apple-ios/p8kmatahap12nosettoappu.md) それらを生成します。
* SDKキー：Pushlyプラットフォームの `ドメイン設定` ページの `概要` > `詳細` > `ドメイン情報` セクションから取得します。

## ステップ 1: PushSDK フレームワークをインポートする

{% tabs %}
{% tab title="Swift Package Manager" %}
PushSDK Framework は Swift と Objective-C の両方に対応しています。

* のみに追加する必要があります。ルートプロジェクトを選択し、その後にメインのアプリケーションターゲット > `一般`
* クリック `+` > `その他を追加` > `パッケージの依存関係を追加` の下の `Frameworks, Libraries, and Embedded Content`
* パッケージ URL を使用して検索: [<mark style="color:青色;">https://github.com/pushly/push-sdk-ios</mark>](https://github.com/pushly/push-sdk-ios)
* 依存関係ルールを次のように設定します: `バージョン範囲` および `1.0.0` < `2.0.0`
* クリック `パッケージを追加`

<figure><img src="/files/99a448da54a76070a90451851a610bc68d948374" alt=""><figcaption></figcaption></figure>

* 次を確認してください `Pushly` オプションにチェックを入れて、次をクリックします `パッケージを追加`

<figure><img src="/files/f705699788df16fc3f3f1ac8a8b3a41d81c91dd6" alt=""><figcaption></figcaption></figure>

* 最後に、次を追加します `Pushly` ライブラリをメインアプリケーションターゲットに

<figure><img src="/files/e6ceaaef3793742f62449ac42333dc408b70bb25" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="CocoaPods" %}
PushSDK Framework は Swift と Objective-C の両方に対応しています。

CocoaPods リンク: <https://cocoapods.org/pods/Pushly>

Podfile に次を追加します:

```
target 'MyApp' do
  pod 'Pushly', '~> 1.1'
end
```

その後、次を実行します `pod install` ターミナル内、または CocoaPods.app から。
{% endtab %}
{% endtabs %}

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

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

アプリの XCode プロジェクト内で次を選択します `File > New > Target`。次を選択します `Notification Service Extension` をiOSテンプレートタブ内で選択して、 `Next`.

<figure><img src="/files/0d74fa664d091c410531eb9ecff49e7516019f10" alt=""><figcaption></figcaption></figure>

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

<figure><img src="/files/70da4bb154a18f120bda98b62a63ce8991f81e66" alt=""><figcaption></figcaption></figure>

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

<img src="/files/f6e3d871b45ca43a08967ec042dd669ed723c05a" alt="" data-size="original">

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

次に、次を追加します `Pushly` ライブラリを Notification Service Extension に:

クリック `+` の下の `Frameworks and Libraries` そして、すでにインポートされた `Pushly` ライブラリを選択します。

<figure><img src="/files/5f7fec4cf4390bd14283643d70b4b6cf224c167b" alt=""><figcaption></figcaption></figure>

次に、新しく作成された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" %}
依存関係エラーは無視できます。たとえば `Module Pushly not found`は、この時点では次回のビルドで解決されるためです。
{% endhint %}

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

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

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

<figure><img src="/files/50bb70546375b351b4daec1b886c44738f1f9f3a" alt=""><figcaption></figcaption></figure>

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

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

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

<figure><img src="/files/ddaf430796151ed89742326cba0b37531feb5624" alt=""><figcaption></figcaption></figure>

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

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

<figure><img src="/files/26812bff850bd6638d723523857e2a406d744acc" alt=""><figcaption></figcaption></figure>

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

{% hint style="info" %}
この時点で Xcode が新しい App Group について警告する場合は、プロビジョニングが完了した後に一覧を更新する必要があるかもしれません。
{% endhint %}

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

ルートプロジェクトを選択し、次に `NotificationServiceExtension > Signing & Capabilities`

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

最後に、「」内の新しく作成された App Group の横にあるチェックボックスをオンにします `NotificationServiceExtension`.

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

まず、次をインポートします `Pushly` AppDelegate 内のライブラリ

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

```swift
import Pushly
```

{% endtab %}

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

```objectivec
@import Pushly;
```

{% endtab %}
{% endtabs %}

AppDelegate の次のコードを追加します `didFinishLaunchingWithOptions` アプリケーションのメソッドに。

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

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

```swift
PushSDK.logLevel = .info
PushSDK.setConfiguration(appKey: "REPLACE_WITH_SDK_KEY", withLaunchOptions: launchOptions)

PushSDK.PushNotifications.showPermissionPrompt() { granted, settings, error in
    // 任意のコールバック
    print("User accepted permissions: \(granted)")
}
```

{% endtab %}

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

```objectivec
PushSDK.logLevel = PNLogLevelInfo;
[PushSDK setConfigurationAppKey:@"REPLACE_WITH_SDK_KEY" withLaunchOptions:launchOptions];

[PushSDKPushNotifications showPermissionPrompt:^(BOOL granted, UNNotificationSettings * _Nonnull settings, NSError * _Nullable error) {
    NSLog(@"User accepted permissions: %@", granted ? @"YES" : @"NO")
}];
```

{% endtab %}
{% endtabs %}

## ステップ 6: 実装をテストする

正しくビルドされることを確認するために、実機の iOS デバイスでアプリを実行します。

{% hint style="info" %}
**注：** XCode シミュレーターはリモートプッシュ通知をサポートしていません。物理デバイスを使用する必要があります。
{% endhint %}

前のステップで追加したコードにより、アプリを開くとプッシュ許可ダイアログが表示されます。これは次を使用してカスタマイズできます [<mark style="color:青色;">SDK メソッド</mark>](/pushly-ja/integration/implementation-steps/apple-ios/sdk-swift-obj-c/sdkmesoddo.md#manually-triggering-the-permission-dialog) を使用して、ダイアログを表示するタイミングを制御することでカスタマイズできます。

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

## 次のステップ

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

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


---

# 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://documentation.pushly.com/pushly-ja/integration/implementation-steps/apple-ios/sdk-swift-obj-c.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.
