Sign In With Apple Implementation With Error Handling Using Swift

Vishal Jadav
Mac O’Clock
Published in
3 min readJul 12, 2020

Apple has introduced an efficient, secure and easy way to sign in to apps and websites using sign in with apple. Instead of filling out forms, verifying email addresses, and choosing new passwords, you can use Sign in with Apple to set up an account and start using your app right away. Using sign in with apple will allow users to set up an account and sign in to your apps and associated websites with their personal apple id. Sign in with Apple works natively on iOS, macOS, tvOS, and watchOS.

# Important Points

  • Users need to enable two factor verification in their ios device. if you wanted to know how to enable it visit this link : https://support.apple.com/en-us/HT204915
  • Developer should have paid apple developer account to enable sign in with apple in your project app.
  • Sign in with apple works on ios 13 or later. If you wanted to give support for earlier ios versions or any other platform you can check apple’s documentation through this link : Incorporating Sign in with Apple into Other Platforms.
Photo by Alasdair Elmes on Unsplash

Lets Do Implementation :

  • First of all create a new project or open your existing project using xcode.
  • Then enable Sign In With Apple capability in Signing & Capabilities menu. Remember you should have paid apple developer account to enable it else you won’t see this option.
  • Now go to your view controller and use below code:
import UIKit
import AuthenticationServices
class LogInVC: UIViewController {
// MARK:- Memory Management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } deinit {
}
// Mark : Added Sign In With Apple Button private func setupLoginProviderView() { let btnAuthorization = ASAuthorizationAppleIDButton() self.view.addSubview(btnAuthorization) btnAuthorization.translatesAutoresizingMaskIntoConstraints = false btnAuthorization.widthAnchor.constraint(equalToConstant: 240.0).isActive = true btnAuthorization.heightAnchor.constraint(equalToConstant: 45.0).isActive = true btnAuthorization.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true btnAuthorization.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true btnAuthorization.addTarget(self, action: #selector(handleLogInWithAppleIDButtonPress), for: .touchUpInside) }// Mark: Sign In With Apple Action Handler @objc private func handleLogInWithAppleIDButtonPress() {
let appleIDProvider = ASAuthorizationAppleIDProvider() let request = appleIDProvider.createRequest() request.requestedScopes = [.fullName, .email] let authorizationController = ASAuthorizationController(authorizationRequests: [request]) authorizationController.delegate = self authorizationController.presentationContextProvider = self authorizationController.performRequests()} func showMesssage (errorMsg:String) { let alert = UIAlertController(title: "Error", message: errorMsg, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil)}
// MARK:- ViewController LifeCycle Method override func viewDidLoad() { super.viewDidLoad() setupLoginProviderView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) }}
// MARK:- ASAuthorizationController delegate Methods Implementationextension LogInVC : ASAuthorizationControllerDelegate { func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { if let err = error as? ASAuthorizationError { switch err.code { case .canceled: self.showMesssage(errorMsg: "User did cancel authorization.") return case .failed: self.showMesssage(errorMsg: "Authorization failed.") case .invalidResponse: self.showMesssage(errorMsg: "Authorization returned invalid response.") case .notHandled: self.showMesssage(errorMsg: "Authorization not handled.") case .unknown: if controller.authorizationRequests.contains(where: { $0 is ASAuthorizationPasswordRequest }) { self.showMesssage(errorMsg: "Unknown error with password auth, trying to request for appleID auth..") let requestAppleID = ASAuthorizationAppleIDProvider().createRequest() requestAppleID.requestedScopes = [.email, .fullName] requestAppleID.requestedOperation = .operationImplicit let controller = ASAuthorizationController(authorizationRequests: [requestAppleID]) controller.delegate = self controller.presentationContextProvider = self controller.performRequests() return} else { self.showMesssage(errorMsg: "Unknown error for appleID auth.")} default: self.showMesssage(errorMsg: "Unsupported error code.") } }}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential { print(appleIDCredential.user) print(appleIDCredential.fullName?.givenName ?? "") print(appleIDCredential.fullName?.familyName ?? "") print(appleIDCredential.email ?? "")
if let identityTokenData = appleIDCredential.identityToken,
let identityTokenString = String(data: identityTokenData, encoding: .utf8) { print("Identity Token \(identityTokenString)") } // Perform Redirection // let viewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC // self.navigationController?.pushViewController(viewController, animated: true) } }}extension LogInVC : ASAuthorizationControllerPresentationContextProviding { func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { return self.view.window! }}

Thank you for reading :)

--

--