Sign In with Apple using Swift

Users can create an account and use their Apple ID to log in to their apps and websites by using Sign In with Apple.

Apple enables users to use their Apple IDs to log into applications. Instead of filling out forms and creating new passwords, users can sign in with Apple to begin using the app immediately. Apple keeps no record of what the user does within the program. Apple only gathers the user’s name and email address; it doesn’t gather much more information.

In this Blog, we will go over enabling Apple Sign-in in the Swift-developed iOS application. 

Please make sure you complete the following tasks before continuing:

1. Set up your Apple Developer Account’s app ID.

Log into your Apple developer account and navigate to the Certificates, Identifiers, and Profiles section to configure the app ID. Choose the application ID from the list of identifiers used in the XCode project, verify that the sign-in with Apple capability is enabled, and then press the save button. Examine the picture below.

2. Set up the XCode project.

  1. Launch the Xcode project.
  2. Add “Sign in With Apple” Capability in Xcode.
  3. Project Navigator → Choose Project → Choose Target.
  4. Navigate to Signing & Capabilities in Project Editor.
  5. To add Capability, press the + symbol. Go to Capability Library and search for Sign In with Apple Capability.

6. Double-click the “Add” button.

Use Apple Entitlement to Log in

If you enable capability with an Apple Developer Account, you must add entitlement. You don’t need to directly edit an App ID or the entitlements file when configuring capabilities using Xcode because Xcode takes care of the associated entitlements. If you enable capability with an Apple Developer Account, you must add entitlement. You don’t need to directly edit an App ID or the entitlements file when configuring capabilities using Xcode because Xcode takes care of the associated entitlements.

<?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>com.apple.developer.applesignin</key>
<array>
<string>Default</string>
</array>
</dict>
</plist>

Configuring and Using Sign-In Features

We can now implement the actual code to add sign-in with Apple functionality as we have finished configuring the developer account and XCode. We must use the Authentication Services framework to enable users to sign into your services using their Apple ID.

import AuthenticationServices

The first thing we need to do is add an Apple Sign-in button to our View Controller which will be called when the button is tapped.

import UIKit

import AuthenticationServices

class ViewController: UIViewController, ASAuthorizationControllerDelegate {

    @IBOutlet var appleBtn: UIButton?

    override func viewDidLoad() {

        super.viewDidLoad()

        appleBtn?.layer.borderWidth = 1

        appleBtn?.layer.borderColor = UIColor.white.cgColor

    }

    @IBAction func AppleLoginAction() {

    }

}

AppleLoginAction() is the function where we will now request the user to verify their Apple ID. We generate the request object using the appleIdProvider object’s createRequest() method. The request object, which can be either full name, email, or both, can be used to set the desired scopes. Additionally, the ASAuthorizationControllerDelegate protocol must be followed by our view controller to use its delegate methods.

@IBAction func AppleLoginAction() {
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let authorizationController =        ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.performRequests()
    }

After a successful sign-in, the below function is called.

func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
  if let appleIDCredential = authorization.credential as?    ASAuthorizationAppleIDCredential {

   let userIdentifier = appleIDCredential.user
   let fullName = appleIDCredential.fullName
   let email = appleIDCredential.email
   print(“User id is \(userIdentifier) \n Full Name is \(String(describing: fullName)) \n Email id is \(String(describing: email))”) 
}
}

We can handle the errors in the following delegate method.   

func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
 // Error
}

Verify the Credential State

When the application launches, we can also verify the user’s credentials. The getCredentialState() function in the AppDelegate didFinishLaunchingWithOptions method must be called to achieve this. In the didFinishLaunchingWithOptions method, add the following code.

let appleIDProvider = ASAuthorizationAppleIDProvider()
appleIDProvider.getCredentialState(forUserID: KeychainItem.currentUserIdentifier) {  (credentialState, error) in
     switch credentialState {
        case .authorized:
            // The Apple ID credentials are authentic.
            break
        case .revoked:
            // The Apple ID is no longer valid.
            break
        case .notFound:
            // Please display the sign-in user interface as no credential    was found.
        default:
            break 
     }
}

After finishing the code, let’s launch the application in the simulator to see if Apple Sign-In is enabled or not.

The Apple Sign-In Process is Complete!

I’m grateful. I hope this is useful to you. Kindly inform me if you have any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *