Skip to content

Commit

Permalink
Add react native facilities for the presentation anchor
Browse files Browse the repository at this point in the history
  • Loading branch information
itaihanski committed Mar 5, 2025
1 parent 98fb772 commit 56f481a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/internal/others/Internal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,37 @@ class DefaultPresentationContextProvider: NSObject, ASWebAuthenticationPresentat
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return presentationAnchor
}

private var presentationAnchor: ASPresentationAnchor {
#if os(macOS)
#if os(iOS)
return findKeyWindow() ?? ASPresentationAnchor()
#else
return ASPresentationAnchor()
#else
#endif
}

#if canImport(React)
func waitKeyWindow() async {
for _ in 1...10 {
guard findKeyWindow() == nil else { return }
try? await Task.sleep(nanoseconds: 100 * NSEC_PER_MSEC)
}
}
#endif

#if os(iOS)
private func findKeyWindow() -> UIWindow? {
let scene = UIApplication.shared.connectedScenes
.filter { $0.activationState == .foregroundActive }
.compactMap { $0 as? UIWindowScene }
.first
let keyWindow = scene?.windows

let window = scene?.windows
.first { $0.isKeyWindow }

return keyWindow ?? ASPresentationAnchor()
#endif

return window
}
#endif
}

class AuthorizationDelegate: NSObject, ASAuthorizationControllerDelegate {
Expand Down
4 changes: 4 additions & 0 deletions src/internal/others/WebAuth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ private func presentWebAuthentication(url: URL, accessSharedUserData: Bool, logg
let contextProvider = DefaultPresentationContextProvider()
var cancellation: @MainActor () -> Void = {}

#if canImport(React)
await contextProvider.waitKeyWindow()
#endif

let result: Result<URL?, Error> = await withTaskCancellationHandler {
return await withCheckedContinuation { continuation in
let session = ASWebAuthenticationSession(url: url, callbackURLScheme: WebAuth.redirectScheme) { callbackURL, error in
Expand Down

0 comments on commit 56f481a

Please sign in to comment.