---
title: Ionic 采集
description: 使用 Capacitor 插件在 Ionic 应用中运行 Journey 流程的采集，使用 Human Plugin 创建请求返回的链接。
canonical: https://developer.unico.io/zh-CN/human-plugin/integrations/ionic
locale: zh-CN
generated_by: markdown-export
---

# Ionic 采集

使用本地 Capacitor 插件从 Ionic 应用中打开采集。

您的后端使用 Journey 流程和一个采用您应用 URL scheme 的 `callbackUri` 在 Human Plugin 中创建流程。本地 Capacitor 插件会在 Android 的 Custom Tabs 和 iOS 的 `ASWebAuthenticationSession` 中打开响应里的 `link`。采集结束后，插件完成（resolve），应用接管后续流程。

请保留创建响应中的 Human Plugin `id`。您的后端用它来读取结果。

## 前提条件

- 使用 Capacitor 4 或更高版本的 Ionic
- Xcode 14 或更高版本，以及 Android Studio
- 您应用独有的 URL scheme，例如 `myapp`

## 1. 使用您的 scheme 创建流程

您的后端将该 scheme 作为 `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. 注册您的 scheme

### 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 {
  /** Resolves true when the capture ended, false when the person closed it. */
  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) {
  // The capture ended. Ask your back-end to read the outcome
  // with GET /v1/processes/{id}, using the Human Plugin id.
}
```

## 总结

| 文件 | 用途 |
|---|---|
| `capture-plugin.ts` | Capacitor 插件接口 |
| `CapturePlugin.swift` | iOS：`ASWebAuthenticationSession` |
| `CapturePlugin.kt` | Android：Custom Tabs |
| `Info.plist` | iOS URL scheme |
| `AndroidManifest.xml` | Android intent filter |
| `capture.service.ts` | Angular 服务 |