Apple SignIn in SwiftUI

Swift Diaries
2 min readJul 21, 2021

App preparation

Files using are as follows

  1. SwiftUI_Social_LoginApp.swift (depends on project. @main entry point)
  2. LoginView.swift (for Login Buttons)
  3. LoginViewModel.swift (for Login functionality)
  4. HomeView.swift (to route after login)
  5. CustomSocialLoginButton.swift (custom login button)

Below buttons will be used to trigger social logins in the LoginView.swift

CustomSocialButton(
image: "ic_login_apple",
text: "Sign in with Apple",
color: "black",
action: {
vm.performAppleSignIn()
})
.padding(.top, 5)

Routing

SwiftUI_Social_LoginApp.swift file handles the routing part by checking the availability of the token.

Adding Capabilities

  1. Go to Signing & Capabilities tab and Click on Add Capabilities
  2. Search for Sign in with Apple and select it
  3. Now you may see that it is added as follows

SignIn functionality

In LoginViewModel.swift,

  1. Import library for Apple Signin
import AuthenticationServices

2. Add this code. Remember to conform to ASAuthorizationControllerDelegate

3. performAppleSignIn method will trigger the Apple SignIn request to the Apple server. Here you can set parameters needed to get (Fullname or/and Email)

4. By setting the controller’s delegate to self, you can trigger the protocol methods in this file itself.

a) didCompleteWithAuthorization

b) didCompleteWithError

5. Get the token and perform your next tasks as sending the token to the backend.

CustomSocialLoginButton.swift

HomeView.swift

Following is the code for HomeView. If user wants to logout, the token will be made nil. So the work group of SwiftUI_Social_LoginApp.swift will refresh and check for a token again and shows the login page.

--

--

Swift Diaries

I am an iOS developer and thought of writing day today Swift things for the community :)