Skip to content

Instantly share code, notes, and snippets.

@navsing
Created May 14, 2020 22:01
Show Gist options
  • Select an option

  • Save navsing/61bf6bdb15f217e82c7cedd8e1628875 to your computer and use it in GitHub Desktop.

Select an option

Save navsing/61bf6bdb15f217e82c7cedd8e1628875 to your computer and use it in GitHub Desktop.
final class SignInWithAppleCoordinator: NSObject {
func getApppleRequest() {
let appleIdProvider = ASAuthorizationAppleIDProvider()
let request = appleIdProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authController = ASAuthorizationController(authorizationRequests: [request])
authController.delegate = self
authController.performRequests()
}
private func setUserInfo(for userId: String, fullName: String?, email: String?) {
ASAuthorizationAppleIDProvider().getCredentialState(forUserID: userId) { credentialState, error in
var authState: String?
switch credentialState {
case .authorized: authState = "authorized"
case .revoked: authState = "revoked"
case .notFound: authState = "notFound"
case .transferred: authState = "transferred"
@unknown default:
fatalError()
}
let user = User(fullName: fullName ?? "not provided", email: email ?? "email", authState: authState ?? "unknown")
if let userEncoded = try? JSONEncoder().encode(user) {
UserDefaults.standard.set(userEncoded, forKey: "user")
}
}
}
}
extension SignInWithAppleCoordinator: ASAuthorizationControllerDelegate {
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let credential = authorization.credential as? ASAuthorizationAppleIDCredential {
let fullName = (credential.fullName?.givenName ?? "")
setUserInfo(for: credential.user, fullName: fullName, email: credential.email)
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print("Sign In with Apple ID Error: \(error.localizedDescription)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment