---
title: Ionic でのキャプチャ
description: Human Plugin の作成で返された link を使い、Capacitor プラグインで Ionic アプリ内に Journey フローのキャプチャを実行します。
canonical: https://developer.unico.io/ja/human-plugin/integrations/ionic
locale: ja
generated_by: markdown-export
---

# Ionic でのキャプチャ

ローカルの Capacitor プラグインを使って Ionic アプリからキャプチャを開きます。

バックエンドは、Journey フローと、アプリの URL スキームを使った `callbackUri` を指定して、Human Plugin にプロセスを作成します。ローカルの Capacitor プラグインが、レスポンスの `link` を Android では Custom Tabs で、iOS では `ASWebAuthenticationSession` で開きます。キャプチャが終了するとプラグインが resolve し、アプリに制御が戻ります。

作成のレスポンスの Human Plugin `id` を保持してください。バックエンドはこの `id` で結果を読み取ります。

## 前提条件

- Capacitor 4 以降を使用する Ionic
- Xcode 14 以降、および Android Studio
- `myapp` のような、アプリ固有の URL スキーム

## 1. スキームを指定してプロセスを作成する

バックエンドはスキームを `callbackUri` として送信します。

```json
{
  "flow": "humantoken",
  "clientId": "client-a",
  "correlationId": "order-1001",
  "credential": { "type": "DUI_TYPE_NG_BVN", "value": "<document number>" },
  "callbackUri": "myapp://callback"
}
```

そして `id` と `link` をアプリに返します。

## 2. プラグインのインターフェースを定義する

```typescript
// src/plugins/capture-plugin.ts
import { registerPlugin } from '@capacitor/core';

export interface CapturePlugin {
  openSession(options: { url: string }): Promise<{ callbackUrl: string }>;
}

const Capture = registerPlugin<CapturePlugin>('CapturePlugin');
export default Capture;
```

## 3. iOS プラグインを実装する

```swift
import Capacitor
import AuthenticationServices

@objc(CapturePlugin)
public class CapturePlugin: CAPPlugin, ASWebAuthenticationPresentationContextProviding {
    private var session: ASWebAuthenticationSession?

    @objc func openSession(_ call: CAPPluginCall) {
        guard let urlString = call.getString("url"),
              let url = URL(string: urlString) else {
            call.reject("Invalid URL")
            return
        }

        DispatchQueue.main.async {
            let newSession = ASWebAuthenticationSession(
                url: url,
                callbackURLScheme: "myapp"
            ) { callbackURL, error in
                self.session = nil
                if let callbackURL = callbackURL {
                    call.resolve(["callbackUrl": callbackURL.absoluteString])
                } else {
                    call.reject(error?.localizedDescription ?? "Session cancelled")
                }
            }
            newSession.presentationContextProvider = self
            newSession.prefersEphemeralWebBrowserSession = true
            newSession.start()
            self.session = newSession
        }
    }

    public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let window = windowScene.windows.first else {
            return ASPresentationAnchor()
        }
        return window
    }
}
```

## 4. Android プラグインを実装する

```kotlin
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin

@CapacitorPlugin(name = "CapturePlugin")
class CapturePlugin : Plugin() {

    private var pendingCall: PluginCall? = null

    @PluginMethod
    fun openSession(call: PluginCall) {
        val url = call.getString("url") ?: return call.reject("Missing URL")
        pendingCall = call

        activity.runOnUiThread {
            CustomTabsIntent.Builder().build()
                .launchUrl(activity, Uri.parse(url))
        }
    }

    override fun handleOnNewIntent(intent: Intent) {
        super.handleOnNewIntent(intent)
        intent.data?.let { uri ->
            if (uri.scheme == "myapp") {
                pendingCall?.resolve(JSObject().put("callbackUrl", uri.toString()))
                pendingCall = null
            }
        }
    }
}
```

## 5. スキームを登録する

### iOS

`Info.plist` に追加します。

```xml
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myapp</string>
        </array>
    </dict>
</array>
```

### Android

`AndroidManifest.xml` の、メインの `<activity>` 内に追加します。

```xml
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="myapp" android:host="callback" />
</intent-filter>
```

`build.gradle` に追加します。

```groovy
implementation("androidx.browser:browser:1.5.0")
```

## 6. キャプチャを開始する

プラグインをラップする Angular サービスです。

```typescript
import { Injectable } from '@angular/core';
import Capture from '../plugins/capture-plugin';

@Injectable({ providedIn: 'root' })
export class CaptureService {
  /** キャプチャが終了した場合は true、本人が閉じた場合は false で解決します。 */
  async open(link: string): Promise<boolean> {
    try {
      await Capture.openSession({ url: link });
      return true;
    } catch {
      return false;
    }
  }
}
```

```typescript
const ended = await this.captureService.open(link);
if (ended) {
  // キャプチャが終了しました。バックエンドに、Human Plugin の id を使った
  // GET /v1/processes/{id} で結果を読み取るよう依頼します。
}
```

## まとめ

| ファイル | 用途 |
|---|---|
| `capture-plugin.ts` | Capacitor プラグインのインターフェース |
| `CapturePlugin.swift` | iOS: `ASWebAuthenticationSession` |
| `CapturePlugin.kt` | Android: Custom Tabs |
| `Info.plist` | iOS の URL スキーム |
| `AndroidManifest.xml` | Android の intent filter |
| `capture.service.ts` | Angular サービス |