> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/nfc-wallet-sdk-ios/ja/implement-nfc-wallet/make-payments/implement-contactless-payment/full-implementation-example.md). Agents can also search and read this documentation through its [MCP server](https://docs.payments.thalescloud.io/~gitbook/mcp).

# 完全な実装例

前の手順がどのように連携するかを理解するには、このコードサンプルを使用してください。

以下の操作から非接触決済を開始します。

* **ダブルクリック** (`NFCWindowSceneEvent.presentation`)
* **フィールド検出** (`NFCWindowSceneEvent.readerDetected`)

{% hint style="info" %}
このサンプルでは、個々の実装手順をすでに確認していることを前提としています。
{% endhint %}

### ソースコード全体

{% code title="SceneDelegate.swift" expandable="true" %}

```swift
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    var window: UIWindow?
    var rootViewController: UIViewController?
    let session = ContactlessPaymentSession()
    
    // ダブルクリックまたはフィールド検出を検知した場合、trueに設定する
    var isDefaultPaymentApp = false
    
    // フィールド検出時にエミュレーションを開始する必要がある場合に備えた、iOS 18向けの処理
    var isPaymentOngoing = false
    
    // アプリが実行されていないときに、ダブルクリックまたはフィールド検出の操作で非接触決済を開始できるようにする:
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // このメソッドを使用して、必要に応じて UIWindow `window` を設定し、指定された UIWindowScene `scene` に関連付けます。
        // ストーリーボードを使用している場合、`window` プロパティは自動的に初期化され、シーンに関連付けられます。
        // このデリゲートは、接続中のシーンやセッションが新規であることを意味するものではありません（代わりに `application:configurationForConnectingSceneSession` を参照してください）。
        guard let windowScene = (scene as? UIWindowScene) else { return }
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let landingVC = storyboard.instantiateViewController(identifier: "LandingSB")
        
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = landingVC
        window.makeKeyAndVisible()
        self.window = window
        
        rootViewController = landingVC
        
        // シーンに入るたびにfalseに設定する
        isDefaultPaymentApp = false
        
        if #available(iOS 17.4, *) {
            if let nfcEvent = connectionOptions.nfcEvent {
                switch nfcEvent {
                case .presentation:
                    // デフォルトの決済アプリの場合にのみトリガーされるため、trueに設定する
                    isDefaultPaymentApp = true
                    startPayment()
                case .readerDetected:
                    // デフォルトの決済アプリの場合にのみトリガーされるため、trueに設定する
                    isDefaultPaymentApp = true
                    handleFieldDetect(withCurrentVC: window.rootViewController)
                @unknown default: break
                }
            }
        }
    }
    
    func sceneDidEnterBackground(_ scene: UIScene) {
        // 別のアプリをデフォルトに設定できるため、シーンを離れるたびにfalseに設定する
        isDefaultPaymentApp = false
        
        // シーンがフォアグラウンドからバックグラウンドに移行するときに呼び出されます。
        // データを保存し、共有リソースを解放し、シーン固有の状態情報を十分に保存して、
        // シーンを現在の状態に復元できるようにします。
        if #available(iOS 17.4, *) {
            Task {
                // デフォルトの決済アプリは、セッション開始後、APDUを受信してバックグラウンドで決済を完了します
                // アプリがバックグラウンドに移行するときに処理をキャンセルするためのものです。
                // また、決済画面以外の画面に移動する場合などにも、この操作を行うことを推奨します。
                await session.cancel()
            }
        }
    }
    

}

extension SceneDelegate: NFCWindowSceneDelegate {
    @available(iOS 17.4, *)
    // アプリがバックグラウンドまたはフォアグラウンドにあるときに、ダブルクリックまたはフィールド検出の操作で非接触決済を開始できるようにする:
    func windowScene(_ windowScene: UIWindowScene, didReceiveNFCWindowSceneEvent event: NFCWindowSceneEvent) {
        switch event {
        case .presentation:
            isDefaultPaymentApp = true
            startPayment()
        case .readerDetected:
            isDefaultPaymentApp = true
            handleFieldDetect(withCurrentVC: rootViewController)
        @unknown default: break
        }
    }
}

extension SceneDelegate {
    
    // ダブルクリックで決済を開始するよう、UIに促す
    func displayAlertWithDoubleClickStartPayment(withCurrentVC currentVC: UIViewController?) {
        let alertController = UIAlertController(title: "ダブルクリックして決済を開始してください", message: nil, preferredStyle: .alert)
        alertController.addAction(
            UIAlertAction(title: "OK", style: .default)
        )
        currentVC?.present(alertController, animated: false)
    }
    
    // ダブルクリックの確認を求める必要がある場合は true を返す
    @available(iOS 17.4, *)
    func handleFieldDetect(withCurrentVC currentVC: UIViewController?){
        // 通常のフィールド検出として扱うか、進行中の paymentSession に対する readerDetect として扱うかを判定する
        // iOS 18 以降のみ
        if #available(iOS 18, *), isPaymentOngoing {
            // iOS 18 以降で、進行中の決済が readerDetect イベントを受信した場合
            Task {
                try await self.session.startEmulation()
            }
        } else {
            // 次のシナリオでは、通常どおりフィールド検出を処理する:
            // - iOS 17.4 以降。決済が進行中かどうかを問わない。
            // - iOS 18.x。決済が進行中でない場合。
            
            let biometricType = biometricType()
            // 指紋認証の場合は決済を直接開始する
            if biometricType == .touchID {
                startPayment()
            } else {
                displayAlertWithDoubleClickStartPayment(withCurrentVC: currentVC)
            }
        }
    }
    
    func startPayment(withDigitalCardID digitalCardID: String? = nil) {
        Task {
            
            // SDK を初期化する
            try await TSHPay.shared.configure(withVerificationMethod: .userPresence)
            
            if #available(iOS 17.4, *) {
                
                // 決済が進行中であることを示す。フィールド検出と iOS 18 で必要。
                isPaymentOngoing = false
                                
                // デフォルトの決済アプリかどうかを確認し、presentmentIntent が有効かどうかを確認する
                if !isDefaultPaymentApp, !PresentmentIntentWrapper.isValid() {
                    do {
                        // デフォルトの決済アプリの動作を検出できない場合は、presentmentIntentAssertion の取得を試みる
                        try await PresentmentIntentWrapper.acquire()
                        print("presentmentIntent assertion acquired \(PresentmentIntentWrapper.isValid())")
                    } catch {
                        // エラーまたはクールダウン期間が原因で失敗した場合
                        // 少なくともアプリへのリダイレクトを避けるため、エミュレーションを直接開始する必要がある
                    }
                }
                
                if let digitalCardID {
                    print("StartPayment:: with digitalCardID")
                    await session.startPayment(withDigitalCardID: digitalCardID)
                } else {
                    print("StartPayment:: without digitalCardID")
                    await session.startPayment()
                }
                
                
                for await event in await session.eventStream {
                    switch event {
                    case .authenticationRequired(let action):
                        print("StartPayment:: authenticationRequired")
                        Task {
                            action.proceed()
                        }
                    case .authenticationCompleted:
                        print("StartPayment:: authenticationCompleted")
                        isPaymentOngoing = true
                        // シナリオ A: カードを変更
                        // イベント .authenticationCompleted で startEmulation を開始する場合
                        // try await session.startEmulation()
                        break
                    case .posConnected:
                        print("StartPayment:: posConnected")
                        await session.setAlertMessage("POS Connected")
                        // アプリケーションが NFCPresentmentIntentAssertion を取得しない場合、このイベントで startEmulation() を呼び出すことはできない。
                        try await session.startEmulation()
                        break
                    case .posDisconnected:
                        print("StartPayment:: posDisconnected")
                        await session.setAlertMessage("POS Disconnected")
                    case .transactionCompleted(let context):
                        print("StartPayment:: transactionCompleted")
                        await session.setAlertMessage("Transaction Completed")
                        
                        // ユーザーに表示
                        displayTransactionContext(context)
                    case .errorEncountered(let error):
                        switch (error as? ContactlessPaymentSession.Error) {
                        case .cancelled:
                            // エンドユーザーが取引をキャンセルした。
                            break
                        case .maxSessionDurationReached:
                            // 取引がタイムアウトしたことをエンドユーザーに通知する。
                            break
                        case .nfcPermissionNotAccepted:
                            // 権限が許可されていないことをエンドユーザーに通知する。
                            break
                        case .systemEligibilityFailed:
                            // システムが非接触決済の利用要件を満たしていないことをエンドユーザーに通知する。
                            // 例: Apple ID またはデバイスの所在地がEEA内にない。
                            break
                        case .noPaymentKeys:
                            // 補充が必要です。補充ガイドを参照してください。
                            break
                        case .noDefaultCard:
                            // 取引を開始する前にデフォルトカードを設定する必要がある。
                            break
                        case .keychainError:
                            // エラーメッセージをエンドユーザーに表示する
                            break
                        case .apduFailure(let reason):
                            // 再試行
                            break
                        case .unknown(let underlying):
                            // エラーメッセージをエンドユーザーに表示する
                            break
                        case .transmissionError:
                            // デバイスとPOSリーダー間のAPDU交換中に発生したエラー
                            break
                        case .sessionInvalidated:
                            // カードセッションがシステムによって無効化された
                            break
                        case .deviceEnvironmentUnsafe(_):
                            // デバイス環境が安全でないことを示すエラー
                            break
                        case .setDefaultCardFailure:
                            // `startPayment(withDigitalCardID:)` API呼び出し中に、指定されたデジタルカードIDをデフォルトカードとして設定しようとして発生したエラー。
                            break
                        case .invalidDigitalCardID:
                            // ``startPayment(withDigitalCardID:)`` に指定されたデジタルカードIDが無効。
                            break
                        case .authenticationExpired:
                            // 認証が検証された後に決済を行った際に発生したエラー。
                            break
                        case .posNotSupported:
                            // POSのリストに選択されたAIDが含まれていない場合に発生したエラー。
                            break
                        case .cardNotSupported:
                            // このカードは非接触決済に対応していない。
                            break
                        case .cardNotActive:
                            // 選択されたカードは有効ではない。
                            break
                        case .authenticationFailed:
                            // 認証に失敗した場合に発生したエラー。
                            break
                        case .authenticationKeyInvalidated(let underlying):
                            // デバイスのパスコードがオフまたはリセットされたため、セキュリティリセットが実行され、認証キーが無効化された。
                            // このエラーが発生すると、SDKは保存済みの認証情報を自動的に消去する。
                            // アプリはユーザーに再登録の手順を案内する必要がある。
                            // カードを再読み込みするための通知を投稿する。 
                            showAlert(message: underlying.localizedDescription) {
                              NotificationCenter.default.post(name: .didReceiveRequestForReloadCard, object: nil)
                            }
                            break
                        case .biometricNotEnrolled(let message):
                            // 生体認証の登録を促すメッセージをエンドユーザーに表示します。
                            showAlert(message: "\(message)")
                            break
                        @unknown default:
                            break
                        }
                    @unknown default:
                        fatalError("fixme: encountered unknown case")
                    }
                }
                
                isPaymentOngoing = false
            } else {
                // 以前のバージョンへのフォールバック。
                let alertController = UIAlertController(title: "iOS 17.4以降を搭載したデバイスを使用してください", message: nil, preferredStyle: .alert)
                alertController.addAction(
                    UIAlertAction(title: "OK", style: .default)
                )
                rootViewController?.present(alertController, animated: false)
            }
        }
    }
    
    func biometricType() -> LABiometryType {
        let authContext = LAContext()
        if #available(iOS 11, *) {
            authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
            return authContext.biometryType
        }
        return LABiometryType.none
    }
}
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.payments.thalescloud.io/nfc-wallet-sdk-ios/ja/implement-nfc-wallet/make-payments/implement-contactless-payment/full-implementation-example.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
