> ## 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) + "*****マスク済み*****";
          }
          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="アクセストークン: API へのアクセスに使用される、不透明な文字列または JWT 形式の認可資格情報。" cta="用語集を表示" href="/ja/docs/glossary?term=Access+Tokens">アクセストークン</Tooltip>の保存、呼び出し、更新、ユーザープロファイル情報の取得など、Auth0 と Swift でさらに多くのことを行う方法については、[Auth0.swift SDK](/ja/docs/libraries/auth0-swift) を参照してください。また、[Swift Quickstart](/ja/docs/quickstart/native/ios-swift) では、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="クライアントID: Auth0 から登録済みリソースに付与される識別値です。" cta="用語集を表示" href="/ja/docs/glossary?term=Client+Id">クライアントID</Tooltip> とドメインを指定する必要があります。これらは [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's 現在の認証パイプラインを使用するようになり、レガシーエンドポイントにはアクセスしなくなります。デフォルト値は `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 ライブラリのドキュメント](/ja/docs/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 の外観を変更するためのスタイル設定オプションは、[Customization Guide](/ja/docs/libraries/lock-swift/lock-swift-customization)で一通り確認できます。

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

Lock の動作を設定するためのオプションは数多くあります。以下は、Lock を閉じられるようにし、username のみを許可し (メールアドレスは不可) 、表示する画面を Login と Reset Password のみに限定する設定例です。

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

アプリでの Lock の動作を変更するための設定オプションの完全な一覧は、[Configuration Guide](/ja/docs/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: スタイルのカスタマイズオプション](/ja/docs/libraries/lock-swift/lock-swift-customization)
* [Lock.swift: 設定オプション](/ja/docs/libraries/lock-swift/lock-swift-configuration-options)
* [Lock.swift: サインアップ時のカスタムフィールド](/ja/docs/libraries/lock-swift/lock-swift-custom-fields-at-signup)
* [Lock.swift の国際化](/ja/docs/customize/internationalization-and-localization/lock-swift-internationalization)
* [ログアウト](/ja/docs/authenticate/login/logout)
