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

> A widget that provides a frictionless login and signup experience for your native iOS apps.

# 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>;
};

This reference guide will show you how to implement the Lock user interface, and give you the details on configuring and customizing Lock in order to use it as the UI for your authentication needs. However, if you'd like to learn how to do more with Auth0 and Swift, such as how to save, call and refresh <Tooltip tip="Access Token: Authorization credential, in the form of an opaque string or JWT, used to access an API." cta="View Glossary" href="/docs/glossary?term=Access+Tokens">Access Tokens</Tooltip>, get user profile info, and more, check out the [Auth0.swift SDK](/docs/libraries/auth0-swift). Or, take a look at the [Swift Quickstart](/docs/quickstart/native/ios-swift) to walk through complete examples and see options, both for using Lock as the interface, and for using a custom interface.

Check out the [Lock.swift repository](https://github.com/auth0/Lock.swift) on GitHub.

## Requirements

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

## Install

### Cocoapods

If you are using [Cocoapods](https://cocoapods.org), add this line to your `Podfile`:

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

Then run `pod install`.
For more information on Cocoapods, check [their official documentation](https://guides.cocoapods.org/using/getting-started.html).

### Carthage

If you are using [Carthage](https://github.com/Carthage/Carthage), add the following line to your `Cartfile`:

`github "auth0/Lock.swift" ~> 2.0`
Then run `carthage bootstrap`.
For more information about Carthage usage, check [their official documentation](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos).

### SPM

If you are using the Swift Package Manager, open the following menu item in Xcode:

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

In the **Choose Package Repository** prompt add this url:

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

Then press **Next** and complete the remaining steps.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  For further reference on SPM, check the [official documentation](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app).
</Callout>

## Set up

### Integrate with your Application

Lock needs to be notified when the application is asked to open a URL. You can do this in the `AppDelegate` file.

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

### Import Lock

Import **Lock** wherever you'll need it

`import lock`

### Auth0 Credentials

In order to use Lock you need to provide your Auth0 <Tooltip tip="Client ID: Identification value given to your registered resource from Auth0." cta="View Glossary" href="/docs/glossary?term=Client+Id">Client Id</Tooltip> and Domain, which can be found in your [Auth0 Dashboard](https://manage.auth0.com/#), under your Application's settings.

In your application bundle you can add a `plist` file named `Auth0.plist` that will include your credentials with the following format.

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" />

## Implementation of Lock Classic

Lock Classic handles authentication using Database, Social, and Enterprise connections.

### OIDC Conformant Mode

It is strongly encouraged that this SDK be used in OIDC Conformant mode. When this mode is enabled, it will force the SDK to use Auth0's current authentication pipeline and will prevent it from reaching legacy endpoints. By default this is `false`

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

To show Lock, add the following snippet in your 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)
```

## Use Auth0.Swift Library to access user profile

To access user profile information, you will need to use the `Auth0.Swift` library:

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

Check out the [Auth0.Swift Library Documentation](/docs/libraries/auth0-swift) for more information about its uses.

## Specify Connections

Lock will automatically load the connections configured for your application. If you wish to override the default behavior, you can manually specify which connections it should display to users as authentication options. This can be done by calling the method and supplying a closure that can specify the connection(s).

Adding a database connection:

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

Adding multiple social connections:

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

## Styling and Customization

Lock provides many styling options to help you apply your own brand identity to Lock using `withStyle`. For example, changing the primary color and header text of your Lock widget:

### Customize your title, logo, and primary color

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

You can see the complete set of styling options to alter the appearance of Lock for your app in the [Customization Guide](/docs/libraries/lock-swift/lock-swift-customization).

## Configuration Options

There are numerous options to configure Lock's behavior. Below is an example of Lock configured to allow it to be closable, to limit it to only usernames (and not emails), and to only show the Login and Reset Password screens.

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

You can see the complete set of behavior configuration options to alter the way Lock works for your app in the [Configuration Guide](/docs/libraries/lock-swift/lock-swift-configuration-options).

## Password Manager Support

By default, password manager support using [1Password](https://1password.com/) is enabled for database connections. 1Password support will still require the user to have the 1Password app installed for the option to be visible in the login and signup screens. You can disable 1Password support using the enabled property of the passwordManager.

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

By default the `appIdentifier` will be set to the app's bundle identifier and the `displayName` will be set to the app's display name. You can customize these as follows:

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

You will need to add the following to your app's `info.plist`:

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

## Learn more

* [Lock.swift: Style Customization Options](/docs//libraries/lock-swift/lock-swift-customization)
* [Lock.swift: Configuration Options](/docs/libraries/lock-swift/lock-swift-configuration-options)
* [Lock.swift: Custom Fields at Signup](/docs/libraries/lock-swift/lock-swift-custom-fields-at-signup)
* [Lock.swift Internationalization](/docs/customize/internationalization-and-localization/lock-swift-internationalization)
* [Logout](/docs/authenticate/login/logout)
