Skip to content

Instantly share code, notes, and snippets.

@cnbrown04
Created July 24, 2024 21:43
import SwiftUI
import AuthenticationServices
import SafariServices
struct ContentView: View {
@State private var isPresented = false
@State private var token: String?
var body: some View {
VStack {
if let token = token {
Text("Authenticated with token: \(token)")
} else {
Button("Sign In") {
isPresented = true
}
}
}
.sheet(isPresented: $isPresented) {
SafariView(url: URL(string: "https://aero-web-alpha-d0932c904dc1.herokuapp.com/api/auth/signin")!) { callbackURL in
// Handle the callback URL here
if let token = extractToken(from: callbackURL) {
self.token = token
self.isPresented = false
}
}
}
}
private func extractToken(from url: URL) -> String? {
// Implement token extraction logic here
// This is a placeholder implementation
return url.absoluteString.components(separatedBy: "token=").last
}
}
struct SafariView: UIViewControllerRepresentable {
let url: URL
let onFinish: (URL) -> Void
func makeUIViewController(context: Context) -> SFSafariViewController {
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = false
let controller = SFSafariViewController(url: url, configuration: config)
controller.dismissButtonStyle = .close
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: SFSafariViewController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, SFSafariViewControllerDelegate {
let parent: SafariView
init(_ parent: SafariView) {
self.parent = parent
}
func safariViewController(_ controller: SFSafariViewController, initialLoadDidRedirectTo URL: URL) {
// Check if the URL is your callback URL
if URL.absoluteString.starts(with: "your-app-scheme://callback") {
controller.dismiss(animated: true) {
self.parent.onFinish(URL)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment