---
title: Sign In with Apple
slug: back4app/UkrSV0TiOdATQliyRf47P
description: In this guide you wil learn how to log in a user using an Apple account
image: https://www.back4app.com/images/logo-social.png
createdAt: 2024-03-11T17:27:40.540Z
---

# Sign In with Apple

## Introduction

When integrating third-party sign-in methods on an iOS app, it is mandatory to add the sign in with Apple option as an additional alternative. For this purpose, Apple introduced the **AuthenticationServices** framework. This framework allows developers to seamlessly integrate a **Sign in with Apple** button on any Xcode project.

In [this repository](https://github.com/templates-back4app/ios-sign-in-with-apple) we provide a simple Xcode template where you can test the different sign in methods we are implementing. This example was already introduced in the [log in guide](https://www.back4app.com/docs/ios/parse-swift-sdk/users/user-log-in). You can revisit it for more details about the project.

## Prerequisites

:::hint{type="info"}
**To complete this quickstart, you need:**

- A recent version of Xcode.
- An Apple developer account with non-personal developer team.
- An app created at Back4App.
  - Follow the [New Parse App tutorial](https://www.back4app.com/docs/get-started/new-parse-app) to learn how to create a Parse app at **Back4App**.
  - **Note:&#x20;**&#x46;ollow the [Install Parse SDK (Swift) Tutorial](https://www.back4app.com/docs/ios/parse-swift-sdk) to create an Xcode Project connected to **Back4App**.
:::

## Goal

To integrate a user sign-in feature using the **AuthenticationServices** framework and **ParseSwift SDK**.

## 1 - Setting up Sign in with Apple

- Once we have the Xcode project [linked](https://www.back4app.com/docs/ios/parse-swift-sdk/install-sdk) to the **Back4App** application, we proceed to add the Sign in with Apple capability. To do this, select your project from the project navigator and go to the targets section. Select the main target and go to the **Signing & Capabilities** tab, then click on the **+ Capability** button and add the **Sign in with Apple** capability:

![](https://api.main.archbee.co/api/optimize/yD3zCY-NNBBIfd0uqcfR5/-eKZlYW8EWK01XSPlf1uG_image.png)

This is the only configuration needed to start integrating a **Sign in with Apple** method on an iOS app.

## 2 - Using the AuthenticationServices framework with ParseSwift

The sign in with Apple flow can be completed in three stages. But before, let us add and set up the button to be used to present the **Sign in with Apple** flow. In the <font color="#2166ae">`LogInController`</font>class we add this button:

```swift
1   // LogInController.swift file
2   import AuthenticationServices
3   ...
4
5   class LogInController: UIViewController {
6     ...
7
8     private let signInWithAppleButton: UIButton = {
9       let button = UIButton(type: .system)
10      button.setImage(UIImage(named: "appleIcon"), for: .normal)
11      button.imageView?.contentMode = .scaleAspectFit
12      return button
13    }()
14
15    override func viewDidLoad() {
16      super.viewDidLoad()
17      // ...
18      // Layout configuration
19      // ...
20
21      signInWithAppleButton.addTarget(self, action: #selector(handleSignInWithApple), for: .touchUpInside)
22    }
23  }
24
25  // MARK: - Sign in with Apple section
26  extension LogInController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
27    @objc fileprivate func handleSignInWithApple() {
28      // TODO: Here we will implement the sign in procedure
29    }
30
31     // ASAuthorizationControllerDelegate
32    
33    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
34      // TODO: Handle the sign-in result
35    }
36    
37    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
38      showMessage(title: "Error", message: error.localizedDescription)
39    }
40    
41    // ASAuthorizationControllerPresentationContextProviding
42  
43    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
44      guard let window = view.window else { fatalError("No UIWindow found!") }
45      return window
46    }
47  }
```

Note that the <font color="#2166ae">`LogInController`</font> conforms to two new protocols: <font color="#2166ae">`ASAuthorizationControllerDelegate`</font> and <font color="#2166ae">`ASAuthorizationControllerPresentationContextProviding`</font>. The first protocol allows us to delegate the sign-in result to the <font color="#2166ae">`LogInController`</font> class. The second protocol is to determine the <font color="#2166ae">`UIWindow`</font> where the sign-in sheet is displayed.

We now implement the flow in the <font color="#2166ae">`handleSignInWithApple()`</font> method.

- In the first stage, we prepare the request and the form. The request is constructed by the <font color="#2166ae">`ASAuthorizationAppleIDRequest`</font> class. We get an instance of this class from the <font color="#2166ae">`ASAuthorizationAppleIDProvider`</font> provider and the form by the <font color="#2166ae">`ASAuthorizationControlle`</font>r class. Once we have an instance of the request, we have to provide the scopes we are interested in. So far Apple only gives access to the user’s full name and email. Thus, a standard way to create a request is:

```swift
1   @objc fileprivate func handleSignInWithApple() {
2     let provider = ASAuthorizationAppleIDProvider()
3     let request: ASAuthorizationAppleIDRequest = provider.createRequest()
4     request.requestedScopes = [.fullName, .email]
5     ...
6   }
```

- With this request, we construct an <font color="#2166ae">`ASAuthorizationController`</font> controller. This controller is in charge of displaying a sheet where the user authenticates and gives the corresponding permissions to complete the sign-in process:

```swift
1   @objc fileprivate func handleSignInWithApple() {
2     // As requested by apple, we set up the necessary objects to implement the sign in with Apple flow.
3     // See https://help.apple.com/developer-account/#/devde676e696 for more details
4     let provider = ASAuthorizationAppleIDProvider()
5     let request: ASAuthorizationAppleIDRequest = provider.createRequest()
6     request.requestedScopes = [.fullName, .email]
7 
8     let authorizationController = ASAuthorizationController(authorizationRequests: [request])
9     authorizationController.delegate = self // Here self is a reference to LoginController
10    authorizationController.presentationContextProvider = self // Here self is a reference to LoginController
11
12    // Presents the sign in with Apple sheet and the result will be handled by the ASAuthorizationControllerDelegate delegate
13    authorizationController.performRequests()
14  }
```

- In the last stage we handle the sign-in result. This is returned via the delegate method <font color="#2166ae">`authorizationController(controller:didCompleteWithAuthorization:)`</font>. The last argument in this method is an <font color="#2166ae">`ASAuthorization`</font> class containing all the necessary information about the Apple ID and credentials. This stage is where we associate a <font color="#2166ae">`User`</font> object and perform the log in to the <font color="#2166ae">`Back4App`</font> application. This <font color="#2166ae">`User`</font> object has the following structure (see the [Login guide](https://www.back4app.com/docs/ios/parse-swift-sdk/users/user-log-in) for more details):

```swift
1   import ParseSwift
2
3   struct User: ParseUser {
4     ...
5  
6     var username: String?
7     var email: String?
8     var emailVerified: Bool?
9     var password: String?
10  
11    var age: Int?
12  }
```

Now, we create a <font color="#2166ae">`User`</font> object from the data contained in the <font color="#2166ae">`ASAuthorization`</font> result. We accomplish this by instantiating a <font color="#2166ae">`ParseApple`</font> object (from <font color="#2166ae">`User.apple`</font>) and call the <font color="#2166ae">`login(user:identityToken:)`</font> method:

```swift
1   // MARK: - Sign in with Apple section
2   extension LogInController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
3     ...
4     // ASAuthorizationControllerDelegate
5  
6     func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
7       // We cast the (ASAuthorization) authorization object to an ASAuthorizationAppleIDCredential object
8       guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {
9         return showMessage(title: "Sign in with Apple", message: "Invalid credential")
10    }
11    
12      guard let identityToken = credential.identityToken else {
13        return showMessage(title: "Sign in with Apple", message: "Token not found")
14      }
15        
16      // We log in the user with the token generated by Apple
17      User.apple.login(user: credential.user, identityToken: identityToken) { [weak self] result in
18        switch result {
19        case .success(let user):
20          // After the login succeeded, we send the user to the home screen
21          // Additionally, you can complete the user information with the data provided by Apple
22          let homeController = HomeController()
23          homeController.user = user
24          
25          self?.navigationController?.pushViewController(homeController, animated: true)
26        case .failure(let error):
27          self?.showMessage(title: "Error", message: error.message)
28        }
29      }
30    }
31  }
```

## 3 - Verifying user sign in and session creation

To make sure that the Google sign-in worked, you can look at your **Back4App** application dashboard and see the new <font color="#2166ae">`User`</font> containing the Facebook <font color="#2166ae">`authData`</font> parameters.

![](https://api.main.archbee.co/api/optimize/yD3zCY-NNBBIfd0uqcfR5/0YRyPhXNe7GIB2DQTTOAu_image.png)

You can also verify that a valid session was created in the dashboard, containing a pointer to the corresponding <font color="#2166ae">`User`</font> object.

![](https://api.main.archbee.co/api/optimize/yD3zCY-NNBBIfd0uqcfR5/aCG29yJZGv_WG6O4nZoit_image.png)

## 4 - Linking an existing User to an Apple ID

In case your iOS App requires relating an Apple ID to an existing user in your **Back4App** platform, the <font color="#2166ae">`ParseApple<User>`</font> object implements the method <font color="#2166ae">`link(user:identityToken:completion:)`</font> where you pass the <font color="#2166ae">`user`</font> value and the <font color="#2166ae">`identityToken`</font> from a <font color="#2166ae">`ASAuthorizationAppleIDCredential`</font> credential

```swift
1   let credential: ASAuthorizationAppleIDCredential
2
3   guard let identityToken = credentials.identityToken else {
4     return showMessage(title: "Sign in with Apple", message: "Token not found")
5   }
6
7   User.apple.link(user: credential.user, identityToken: identityToken){ result in
8     switch result {
9     case .success(let user):
10      // Linking succeeded, user object now is linked to the corresponding Apple ID
11    case .failure(let error):
12      // Linking failed, handle the error
13    }
14  }
```

## 5 - Run the app

You can go to this [repository](https://github.com/templates-back4app/ios-sign-in-with-apple) and download the example project. Before running the project, make sure you set up the provisioning profiles with the ones associated with your developer account.

## Conclusion

At the end of this guide, you learned how to sign in or link existing **Back4App** users on iOS using the sign in with Apple.
