Skip to content

Instantly share code, notes, and snippets.

@Ilesh
Created March 14, 2021 14:33
Show Gist options
  • Save Ilesh/7ad476d028c8e0e57bc0b424fd33baef to your computer and use it in GitHub Desktop.
Save Ilesh/7ad476d028c8e0e57bc0b424fd33baef to your computer and use it in GitHub Desktop.
Simple and easy class for the apple sign In. Please check the description for how to use this class. If you find helpful this class please share and give star so others can find it πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘ !!!!
//
// IPAppleSignIn.swift
// KrunalShah
//
// Created by Ilesh on 03/03/21.
// Copyright Β© 2021 Technopear. All rights reserved.
//
//************************ HOW TO USE? *****************************
//
//1. Display apple login button
//if #available(iOS 13.0, *) {
// let authorizationButton = ASAuthorizationAppleIDButton()
// authorizationButton.addTarget(self, action: #selector(handleAuthorizationAppleIDButtonPress), for: .touchUpInside)
// // Disable default width constraints
// authorizationButton.constraints.forEach { (constraint) in
// if (constraint.firstAttribute == .height) {
// constraint.isActive = false
// }
// }
//
// // SET UP CONSTRAINT FOR HEIGHT OR WIDTH
// //appleButton.widthAnchor.constraint(equalToConstant: 150).isActive = true
// authorizationButton.heightAnchor.constraint(equalToConstant: 55).isActive = true
// self.loginProviderStackView.addArrangedSubview(authorizationButton)
//} else {
// // Fallback on earlier versions
//}
//
//2. Handle click methods "handleAuthorizationAppleIDButtonPress"
//
//@objc func handleAuthorizationAppleIDButtonPress() {
// if #available(iOS 13.0, *) {
// IPAppleSignIn.shared.requestAppleLoginInfo { (isSuccess, result) in
// if isSuccess {
// print("Result \(result)")
// // DO YOUR LOGIC HERE
// // API CALL
// }
// }
// } else {
// // Fallback on earlier versions
// }
//}
import Foundation
import AuthenticationServices
@available(iOS 13.0, *)
class IPAppleSignIn : UIViewController, ASAuthorizationControllerPresentationContextProviding, ASAuthorizationControllerDelegate {
static let shared = IPAppleSignIn()
typealias complitionHandler = (Bool,[String:Any]?) -> Swift.Void
private var block : complitionHandler?
func checkStatus(){
// let appleIDProvider = ASAuthorizationAppleIDProvider()
// appleIDProvider.getCredentialState(forUserID: userIdentifier) { (credentialState, error) in
// switch credentialState {
// case .authorized:
// // The Apple ID credential is valid. Show Home UI Here
// break
// case .revoked:
// // The Apple ID credential is revoked. Show SignIn UI Here.
// break
// case .notFound:
// // No credential was found. Show SignIn UI Here.
// break
// default:
// break
// }
// }
}
func requestAppleLoginInfo(_ compliton:@escaping complitionHandler) {
self.block = compliton
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 presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
// Handle error.
self.block?(false,["error":error.localizedDescription])
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
// Create an account in your system.
let defaults = UserDefaults.standard
var result : [String:Any] = [:]
//FOR THIS CLASS PLEASE CHECK OUT THIS LINK: https://gist.github.com/Ilesh/63f6ca0acde8923514529c9e0022d97f
if let _ = appleIDCredential.fullName?.givenName, let _ = appleIDCredential.email {
IPKeyChain.removeValue(service: IPKeyChain.services, account: IPKeyChain.apple_account_name)
IPKeyChain.removeValue(service: IPKeyChain.services, account: IPKeyChain.apple_account_email)
IPKeyChain.removeValue(service: IPKeyChain.services, account: IPKeyChain.apple_Id)
}
if let strAppleID = IPKeyChain.loadPassword(service: IPKeyChain.services, account: IPKeyChain.apple_Id) , strAppleID == appleIDCredential.user {
result["name"] = IPKeyChain.loadPassword(service: IPKeyChain.services, account: IPKeyChain.apple_account_name) ?? ""
result["email"] = IPKeyChain.loadPassword(service: IPKeyChain.services, account: IPKeyChain.apple_account_email) ?? ""
result["login_fb_gp_id"] = strAppleID
defaults.setValue(result, forKey: "dicFBData")
self.block?(true,result)
}else{
IPKeyChain.saveValue(service: IPKeyChain.services, account: IPKeyChain.apple_Id, data: appleIDCredential.user)
IPKeyChain.saveValue(service: IPKeyChain.services, account: IPKeyChain.apple_account_name, data: "\(appleIDCredential.fullName?.givenName ?? "") \(appleIDCredential.fullName?.familyName ?? "")")
IPKeyChain.saveValue(service: IPKeyChain.services, account: IPKeyChain.apple_account_email, data: appleIDCredential.email ?? "")
result["name"] = "\(appleIDCredential.fullName?.givenName ?? "") \(appleIDCredential.fullName?.familyName ?? "")"
result["email"] = appleIDCredential.email ?? ""
result["login_fb_gp_id"] = appleIDCredential.user
defaults.setValue(result, forKey: "dicFBData")
self.block?(true,result)
}
}
}
// func performExistingAccountSetupFlows(compliton:@escaping complitionHandler) {
// self.block = compliton
// // Prepare requests for both Apple ID and password providers.
// let requests = [ASAuthorizationAppleIDProvider().createRequest(),
// ASAuthorizationPasswordProvider().createRequest()]
//
// // Create an authorization controller with the given requests.
// let authorizationController = ASAuthorizationController(authorizationRequests: requests)
// authorizationController.delegate = self
// authorizationController.presentationContextProvider = self
// authorizationController.performRequests()
// }
//DELEGATES
// 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))")
// }
// }
// func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
// switch authorization.credential {
// case let appleIDCredential as ASAuthorizationAppleIDCredential:
//
// // Create an account in your system.
// let userIdentifier = appleIDCredential.user
// let fullName = appleIDCredential.fullName
// let email = appleIDCredential.email
//
// // For the purpose of this demo app, store the `userIdentifier` in the keychain.
// self.saveUserInKeychain(userIdentifier)
//
// // For the purpose of this demo app, show the Apple ID credential information in the `ResultViewController`.
// case let passwordCredential as ASPasswordCredential:
//
// // Sign in using an existing iCloud Keychain credential.
// let username = passwordCredential.user
// let password = passwordCredential.password
//
// // For the purpose of this demo app, show the password credential as an alert.
// DispatchQueue.main.async {
// self.showPasswordCredentialAlert(username: username, password: password)
// }
//
// default:
// break
// }
// }
// private func saveUserInKeychain(_ userIdentifier: String) {
//// do {
//// try KeychainItem(service: "com.example.apple-samplecode.juice", account: "userIdentifier").saveItem(userIdentifier)
//// } catch {
//// print("Unable to save userIdentifier to keychain.")
//// }
// }
// private func showPasswordCredentialAlert(username: String, password: String) {
// let message = "The app has received your selected credential from the keychain. \n\n Username: \(username)\n Password: \(password)"
// let alertController = UIAlertController(title: "Keychain Credential Received",
// message: message,
// preferredStyle: .alert)
// alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
// self.present(alertController, animated: true, completion: nil)
// }
//
// /// - Tag: did_complete_error
}
//extension IPAppleSignIn : ASAuthorizationControllerDelegate {
// 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))") }
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment