> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Lock.swift

> Webアプリにスムーズなログインおよびサインアップエクスペリエンスを提供するネイティブiOSです。

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の構成とカスタマイズの詳細について説明します。ただし、アクセストークンの保存、呼び出し、更新、ユーザー プロファイル情報の取得など、Auth0とSwiftでさらに多くのことを行う方法を学習したい場合は、[Auth0.swift SDK](/docs/ja-jp/libraries/auth0-swift)を確認してください。または、[Swiftクイックスタート](/docs/ja-jp/quickstart/native/ios-swift)を参照して、完全な例を確認し、Lockをインターフェイスとして使用する場合とカスタムインターフェイスを使用する場合の両方のオプションを確認してください。

GitHubの [Lock.swiftリポジトリ](https://github.com/auth0/Lock.swift)を確認してください。

## 要件

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

## インストール

### Cocoapods

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

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

それから`pod install`を実行します。CocoaPodsの詳細は、[公式ドキュメント](https://guides.cocoapods.org/using/getting-started.html)を確認してください。

### Carthage

[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)を確認してください。

### SPM

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

**［File（ファイル）］ > ［Swift Packages］ > ［Add Package Dependency（パッケージ依存関係の追加）］...**

**パッケージリポジトリの選択** プロンプトで、次のURLを追加します。

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

次に、**［Next（次へ）］** を押して残りのステップを完了します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  SPMの詳細については、[公式ドキュメント](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)を確認してください。
</Callout>

## セットアップ

### アプリケーションとの統合

アプリケーションが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)
}
```

### Lockのインポート

必要な場所に**Lock** をインポートする

`lockのインポート`

### Auth0資格情報

Lock を使用するには、[Auth0 Dashboard](https://manage.auth0.com/#)のアプリケーション設定で確認できるAuth0クライアントIDとドメインを提供する必要があります。

アプリケーションバンドルに、次の形式の資格情報を含む`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" />

## Lock Classicの実装

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

### OIDC準拠モード

このSDKはOIDC準拠モードで使用することを強く推奨しています。このモードを有効にすると、SDKはAuth0の現在の認証パイプラインを使用するように強制され、レガシーエンドポイントに到達できなくなります。デフォルトでは`false`です

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

Lockを表示するには、UIViewControllerに次のスニペットを追加します。

```swift lines theme={null}
Lock
    .classic()
    // withConnections, withOptions, withStyle, and so on
    .withOptions {
      $0.oidcConformant = true
      $0.scope = "openid profile"
    }
    .onAuth { credentials in
      // Let's save our credentials.accessToken value
    }
    .present(from: self)
```

## Auth0.Swiftライブラリを使用してユーザープロファイルにアクセスする

ユーザープロファイル情報にアクセスするには、`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ライブラリのドキュメント](/docs/ja-jp/libraries/auth0-swift)で、その使用方法の詳細を確認してください。

## 接続の指定

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)
}
```

## スタイル設定とカスタマイズ

Lockには、`withStyle`を使用して独自のブランド アイデンティティをLockに適用するのに役立つ多くのスタイル設定オプションが用意されています。たとえば、Lockウィジェットのプライマリカラーとヘッダーテキストを変更するには:

### タイトル、ロゴ、プライマリカラーをカスタマイズします

```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/lock-swift-customization)を参照してください。

## 構成オプション

Lockの動作を構成するためのオプションは多数あります。以下は、Lockを閉じられるように設定し、ユーザー名のみ（メールは不可）に制限し、ログイン画面とパスワードのリセット画面のみを表示するように構成した例です。

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

アプリのLock動作を変更するための動作設定オプションの完全なセットについては、[構成ガイド](/docs/ja-jp/libraries/lock-swift/lock-swift-configuration-options)を参照してください。

## パスワードマネージャーのサポート

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

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

デフォルトでは、`appIdentifier`はアプリのバンドル ID に設定され、`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>
```

## もっと詳しく

* [Lock.swift：スタイルカスタマイズのオプション](/docs/ja-jp/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)
