Created
May 14, 2020 22:01
-
-
Save navsing/61bf6bdb15f217e82c7cedd8e1628875 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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