> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> ネイティブiOSアプリで、シームレスなログイン・サインアップ体験を提供するウィジェット。

# Lock.swift

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

このリファレンスガイドでは、Lock のユーザーインターフェースを実装する方法と、認証用 UI として Lock を使用するための設定やカスタマイズの詳細について説明します。一方、<Tooltip tip="Access Token: API にアクセスするために使用される、不透明な文字列または JWT 形式の認可資格情報。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Access+Tokens">Access Tokens</Tooltip> の保存、利用、更新の方法、ユーザープロフィール情報の取得など、Auth0 と Swift でさらにできることを知りたい場合は、[Auth0.swift SDK](/docs/ja-jp/libraries/auth0-swift) をご覧ください。あるいは、[Swift Quickstart](/docs/ja-jp/quickstart/native/ios-swift) で一連の完全な例を確認し、UI として Lock を使用する場合と、カスタムインターフェースを使用する場合の両方の選択肢をご覧ください。

GitHub の [Lock.swift repository](https://github.com/auth0/Lock.swift) もご覧ください。

<div id="requirements">
  ## 動作環境
</div>

* iOS 9+
* Xcode 11.4+ / 12.x
* Swift 4.x / 5.x

<div id="install">
  ## インストール
</div>

<div id="cocoapods">
  ### Cocoapods
</div>

[Cocoapods](https://cocoapods.org) を使用している場合は、次の行を `Podfile` に追加してください。

`pod 'Lock', '~> 2.0'`

その後、`pod install` を実行してください。
Cocoapods の詳細については、[公式ドキュメント](https://guides.cocoapods.org/using/getting-started.html) をご覧ください。

<div id="carthage">
  ### Carthage
</div>

[Carthage](https://github.com/Carthage/Carthage) を使用している場合は、`Cartfile` に次の行を追加します。

`github "auth0/Lock.swift" ~> 2.0`
続いて、`carthage bootstrap` を実行します。
Carthage の使い方の詳細については、[公式ドキュメント](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos) を参照してください。

<div id="spm">
  ### SPM
</div>

Swift Package Manager を使用している場合は、Xcode で次のメニューを開きます。

**File > Swift Packages > Add Package Dependency...**

**Choose Package Repository** 画面で、次の URL を追加します。

`https://github.com/auth0/Lock.swift.git`

続いて **Next** をクリックし、残りの手順を完了します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  SPM の詳細については、[公式ドキュメント](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)を参照してください。
</Callout>

<div id="set-up">
  ## セットアップ
</div>

<div id="integrate-with-your-application">
  ### アプリケーションに組み込む
</div>

アプリケーションが URL を開くよう要求された際には、Lock に通知する必要があります。これは `AppDelegate` ファイルで行えます。

```swift lines theme={null}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  return Lock.resumeAuth(url, options: options)
}
```

<div id="import-lock">
  ### Lock のインポート
</div>

**Lock** が必要な場所でインポートします

`import lock`

<div id="auth0-credentials">
  ### Auth0 の認証情報
</div>

Lock を使用するには、Auth0 の <Tooltip tip="Client ID: Auth0 から登録済みリソースに付与される識別子です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Client+Id">Client Id</Tooltip> と Domain を指定する必要があります。これらは、[Auth0 Dashboard](https://manage.auth0.com/#) のアプリケーション設定で確認できます。

アプリケーションバンドルには、以下の形式で認証情報を含む `Auth0.plist` という名前の `plist` ファイルを追加できます。

export const codeExample = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>ClientId</key>
  <string>{yourClientId}</string>
  <key>Domain</key>
  <string>{yourDomain}</string>
</dict>
</plist>`;

<AuthCodeBlock children={codeExample} language="xml" />

<div id="implementation-of-lock-classic">
  ## Lock Classic の実装
</div>

Lock Classic は、データベース接続、ソーシャル接続、エンタープライズ接続を使用して認証を行います。

<div id="oidc-conformant-mode">
  ### OIDC準拠モード
</div>

このSDKは、OIDC準拠モードで使用することを強く推奨します。このモードを有効にすると、SDKはAuth0の現在の認証パイプラインを使用し、レガシーエンドポイントにアクセスしなくなります。デフォルトでは`false`です

```swift lines theme={null}
.withOptions {
    $0.oidcConformant = true
}
```

Lock を表示するには、次のコードを `UIViewController` に追加します。

```swift lines theme={null}
Lock
    .classic()
    // withConnections、withOptions、withStyle など
    .withOptions {
      $0.oidcConformant = true
      $0.scope = "openid profile"
    }
    .onAuth { credentials in
      // credentials.accessToken の値を保存する
    }
    .present(from: self)
```

<div id="use-auth0swift-library-to-access-user-profile">
  ## Auth0.Swift ライブラリを使用してユーザープロフィールにアクセスする
</div>

ユーザープロフィール情報にアクセスするには、`Auth0.Swift` ライブラリを使用する必要があります。

```swift lines theme={null}
Auth0
   .authentication()
   .userInfo(withAccessToken: accessToken)
   .start { result in
       switch result {
       case .success(let profile):
           print("User Profile: \(profile)")
       case .failure(let error):
           print("Failed with \(error)")
       }
   }
```

使い方の詳細については、[Auth0.Swift Library Documentation](/docs/ja-jp/libraries/auth0-swift)をご覧ください。

<div id="specify-connections">
  ## 接続を指定する
</div>

Lock は、アプリケーションに設定された接続を自動的に読み込みます。デフォルトの動作を変更したい場合は、認証オプションとしてユーザーに表示する接続を手動で指定できます。これには、メソッドを呼び出して、接続を指定するクロージャを渡します。

データベース接続を追加する場合:

```swift lines theme={null}
.withConnections {
    connections.database(name: "Username-Password-Authentication", requiresUsername: true)
}
```

複数のソーシャル接続を追加する:

```swift lines theme={null}
.withConnections {
    connections.social(name: "facebook", style: .Facebook)
    connections.social(name: "google-oauth2", style: .Google)
}
```

<div id="styling-and-customization">
  ## スタイル設定とカスタマイズ
</div>

Lock には、`withStyle` を使って独自のブランドアイデンティティを反映できるよう、さまざまなスタイル設定オプションが用意されています。たとえば、Lock ウィジェットのプライマリカラーやヘッダーテキストを変更できます。

<div id="customize-your-title-logo-and-primary-color">
  ### タイトル、ロゴ、プライマリカラーをカスタマイズ
</div>

```swift lines theme={null}
.withStyle {
  $0.title = "Company LLC"
  $0.logo = LazyImage(named: "company_logo")
  $0.primaryColor = UIColor(red: 0.6784, green: 0.5412, blue: 0.7333, alpha: 1.0)
}
```

アプリ用のLockの見た目を変更するためのスタイル設定オプションについては、[カスタマイズガイド](/docs/ja-jp/libraries/lock-swift/lock-swift-customization)で詳しく確認できます。

<div id="configuration-options">
  ## 設定オプション
</div>

Lock の動作は、さまざまなオプションで設定できます。以下は、閉じることができ、ユーザー名のみを使用可能にし (メールアドレスは使用不可) 、ログイン画面とパスワードリセット画面のみを表示するように設定した Lock の例です。

```swift lines theme={null}
Lock
  .classic()
  .withOptions {
    $0.closable = true
    $0.usernameStyle = [.Username]
    $0.allow = [.Login, .ResetPassword]
  }
```

アプリでの Lock の動作を変更するための設定オプションについては、[Configuration Guide](/docs/ja-jp/libraries/lock-swift/lock-swift-configuration-options)で確認できます。

<div id="password-manager-support">
  ## パスワードマネージャーのサポート
</div>

デフォルトでは、データベース接続で [1Password](https://1password.com/) を使うパスワードマネージャー機能が有効になっています。1Password のサポートは、ログイン画面とサインアップ画面に表示するために、ユーザーの端末に 1Password アプリがインストールされている必要があります。1Password のサポートは、passwordManager の enabled プロパティで無効にできます。

```swift lines theme={null}
.withOptions {
    $0.passwordManager.enabled = false
}
```

デフォルトでは、`appIdentifier` にはアプリのバンドル識別子が設定され、`displayName` にはアプリの表示名が設定されます。これらは次のようにカスタマイズできます。

```swift lines theme={null}
.withOptions {
    $0.passwordManager.appIdentifier = "www.myapp.com"
    $0.passwordManager.displayName = "My App"
}
```

アプリの `info.plist` に次の内容を追加する必要があります:

```xml lines theme={null}
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>org-appextension-feature-password-management</string>
</array>
```

<div id="learn-more">
  ## 詳しくはこちら
</div>

* [Lock.swift: スタイルのカスタマイズ](/docs/ja-jp/libraries/lock-swift/lock-swift-customization)
* [Lock.swift: 設定オプション](/docs/ja-jp/libraries/lock-swift/lock-swift-configuration-options)
* [Lock.swift: サインアップ時のカスタムフィールド](/docs/ja-jp/libraries/lock-swift/lock-swift-custom-fields-at-signup)
* [Lock.swift の国際化](/docs/ja-jp/customize/internationalization-and-localization/lock-swift-internationalization)
* [ログアウト](/docs/ja-jp/authenticate/login/logout)
