Skip to content

Instantly share code, notes, and snippets.

@omarojo
Last active April 8, 2020 10:55
Show Gist options
  • Save omarojo/6c2bdf74f0ef09e0aea0014135c7398f to your computer and use it in GitHub Desktop.
Save omarojo/6c2bdf74f0ef09e0aea0014135c7398f to your computer and use it in GitHub Desktop.
Apple Login
import Foundation
import AuthenticationServices
@available(iOS 13.0, *)
class G8AppleLogin: NSObject{
var authController: ASAuthorizationController!
override init(){
super.init()
}
public func login(showIn: ASAuthorizationControllerPresentationContextProviding){
let request = ASAuthorizationAppleIDProvider().createRequest()
request.requestedScopes = [.fullName, .email]
authController = ASAuthorizationController(authorizationRequests: [request])
authController.delegate = self
authController.presentationContextProvider = showIn
authController.performRequests()
}
}
@available(iOS 13.0, *)
extension G8AppleLogin: ASAuthorizationControllerDelegate{
//MARK: DELEGATES
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
// In this code:
//
// If you receive details, you know it’s a new registration.
// Call your registration method once you receive details.
// Call your existing account method if you don’t receive details.
// // 1
// if let _ = appleIdCredential.email, let _ = appleIdCredential.fullName {
// // 2
// registerNewAccount(credential: appleIdCredential)
// } else {
// // 3
// signInWithExistingAccount(credential: appleIdCredential)
// }
print("User Identifier: \(appleIDCredential.user)")
print("Full Name: \(appleIDCredential.fullName?.givenName ?? "No Name")")
print("Email: \(appleIDCredential.email ?? "No Email Provided")")
print("Real Person Status: \(appleIDCredential.realUserStatus.rawValue)")
print("ID Token: \(String(data: appleIDCredential.identityToken!, encoding: .utf8) ?? "No ID Token Returned")")
print("AuthorizationCode: \(String(data: appleIDCredential.authorizationCode!, encoding: .utf8) ?? "No Authorization Code Returned")")
// Convert Data -> String
guard let authorizationCode = appleIDCredential.authorizationCode, let authCode = String(data: authorizationCode, encoding: .utf8) else
{
print("Problem with the authorizationCode")
return
}
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
// Handle error.
guard let error = error as? ASAuthorizationError else {
return
}
switch error.code {
case .canceled:
G8DLog("Canceled")
case .unknown:
G8DLog("Unknown")
case .invalidResponse:
G8DLog("Invalid Respone")
case .notHandled:
G8DLog("Not handled")
case .failed:
G8DLog("Failed")
@unknown default:
G8DLog("Default")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment