Skip to content

Instantly share code, notes, and snippets.

@laszlotuss
Created May 15, 2024 15:24
Show Gist options
  • Save laszlotuss/1b10d91c25e5709b207f427036a40f04 to your computer and use it in GitHub Desktop.
Save laszlotuss/1b10d91c25e5709b207f427036a40f04 to your computer and use it in GitHub Desktop.
LinkButton for watchOS
//
// LinkButton.swift
//
// Created by Tuss László on 15/05/2024.
//
import SwiftUI
import AuthenticationServices
struct LinkButton<Label: View>: View {
private let url: URL
private let label: Label
// Initializer for LocalizedStringKey
init(_ titleKey: LocalizedStringKey, destination: URL) where Label == Text {
self.url = destination
self.label = Text(titleKey)
}
// Initializer for custom label
init(destination: URL, @ViewBuilder label: () -> Label) {
self.url = destination
self.label = label()
}
var body: some View {
#if os(watchOS)
Button(action: openURL) {
label
}
#else
Link(destination: url) {
label
}
#endif
}
// MARK: - Private
private func openURL() {
let session = ASWebAuthenticationSession(
url: url,
callbackURLScheme: nil
) { callbackURL, error in
// Handle the callback here if needed
if let error = error {
print("Authentication session error: \(error.localizedDescription)")
} else if let callbackURL = callbackURL {
print("Callback URL: \(callbackURL)")
}
}
// Makes the "Watch App Wants To Use example.com to Sign In" popup not show up
session.prefersEphemeralWebBrowserSession = true
// Start the session
session.start()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment