Apple SignIn in SwiftUI

App preparation
Files using are as follows
- SwiftUI_Social_LoginApp.swift (depends on project. @main entry point)
- LoginView.swift (for Login Buttons)
- LoginViewModel.swift (for Login functionality)
- HomeView.swift (to route after login)
- 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
- Go to Signing & Capabilities tab and Click on Add Capabilities
- Search for Sign in with Apple and select it
- Now you may see that it is added as follows
SignIn functionality
In LoginViewModel.swift,
- 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.