Created
September 19, 2024 03:38
-
-
Save mariosaputra/171918f0fea73dbdf7ad535316a3bf21 to your computer and use it in GitHub Desktop.
Sign in with Apple Supabase
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
import SwiftUI | |
import AuthenticationServices | |
import Supabase | |
struct LoginView: View { | |
@State private var isSignedIn = false | |
@State private var signInError: Error? | |
@AppStorage("name") var currentUserName: String? | |
@AppStorage("userID") var signedInUserId: String? | |
@AppStorage("is_signed_in") var isUserSignedIn: Bool = false | |
let supabase = SupabaseClient(supabaseURL: URL(string: "YOUR_PROJECT_URL")!, supabaseKey: | |
"YOUR_PUBLIC_KEY") | |
var body: some View { | |
VStack(spacing: 40) { | |
Spacer() | |
// Logo | |
Image(systemName: "YOUR_LOGO") | |
.resizable() | |
.scaledToFit() | |
.frame(width: 150, height: 150) | |
// Title | |
Text("YOUR_APP_NAME") | |
.font(.largeTitle) | |
.fontWeight(.semibold) | |
Spacer() | |
SignInWithAppleButton(.signIn) { request in | |
request.requestedScopes = [.fullName, .email] | |
} onCompletion: { result in | |
switch result { | |
case .success(let authResults): | |
print("Authorization successful") | |
handleSignInWithApple(authorization: authResults) | |
case .failure(let error): | |
print("Authorization failed: \(error.localizedDescription)") | |
signInError = error | |
} | |
} | |
.frame(height: 55) | |
.padding() | |
} | |
.padding(40) | |
.multilineTextAlignment(.center) | |
.alert(isPresented: Binding<Bool>.constant(signInError != nil)) { | |
Alert(title: Text("Sign In Error"), message: Text(signInError?.localizedDescription ?? "Unknown error"), dismissButton: .default(Text("OK"))) | |
} | |
} | |
func handleSignInWithApple(authorization: ASAuthorization) { | |
guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else { | |
print("Unable to fetch Apple ID Credential") | |
return | |
} | |
guard let identityToken = appleIDCredential.identityToken, | |
let tokenString = String(data: identityToken, encoding: .utf8) else { | |
print("Unable to fetch identity token") | |
return | |
} | |
Task { | |
do { | |
let session = try await supabase.auth.signInWithIdToken(credentials: .init(provider: .apple, idToken: tokenString)) | |
DispatchQueue.main.async { | |
self.currentUserName = appleIDCredential.fullName?.givenName | |
self.signedInUserId = session.user.id.uuidString | |
self.isUserSignedIn = true | |
self.isSignedIn = true | |
} | |
} catch { | |
print("Error signing in with Supabase: \(error)") | |
DispatchQueue.main.async { | |
self.signInError = error | |
} | |
} | |
} | |
} | |
} | |
#Preview { | |
LoginView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment