Skip to content

Instantly share code, notes, and snippets.

@pallavtrivedi03
Created April 30, 2020 12:00
Show Gist options
  • Save pallavtrivedi03/a16206e7f1e52ab981ebcf8f098e3e60 to your computer and use it in GitHub Desktop.
Save pallavtrivedi03/a16206e7f1e52ab981ebcf8f098e3e60 to your computer and use it in GitHub Desktop.
Sign in with Apple
import UIKit
import AuthenticationServices
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupAppleSignIn()
}
func setupAppleSignIn() {
if #available(iOS 13.0, *) {
let appleSignInButton = ASAuthorizationAppleIDButton(type: .default, style: .whiteOutline)
appleSignInButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
appleSignInButton.layer.cornerRadius = 22
appleSignInButton.clipsToBounds = true
appleSignInButton.addTarget(self, action: #selector(didClickOnAppleSignIn), for: .touchUpInside)
//Add appleSignInButton to your view as subview
} else {
// Fallback on earlier versions
}
}
@objc func didClickOnAppleSignIn() {
if #available(iOS 13.0, *) {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
} else {
// Fallback on earlier versions
}
}
}
extension LoginViewController: ASAuthorizationControllerDelegate {
// Failed authorization
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print(error.localizedDescription)
}
// Successful authorization
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
let appleId = appleIDCredential.user
let appleUserFirstName = appleIDCredential.fullName?.givenName
let appleUserLastName = appleIDCredential.fullName?.familyName
let appleUserEmail = appleIDCredential.email
//send these details to server
} else if let passwordCredential = authorization.credential as? ASPasswordCredential {
let username = passwordCredential.user
let password = passwordCredential.password
}
}
}
extension LoginViewController: ASAuthorizationControllerPresentationContextProviding {
@available(iOS 13.0, *)
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment