@@ -12,6 +12,9 @@ private extension Notification.Name {
1212final class KirieManager : NSObject {
1313 static let shared = KirieManager ( )
1414
15+ private static let hostWindowRetryDelay : TimeInterval = 0.1
16+ private static let maxHostWindowResolveAttempts = 50
17+
1518 private let notificationCenter = NotificationCenter . default
1619 private let sessionID = UUID ( ) . uuidString. lowercased ( )
1720 private let resourceURLSchemeHandler = KirieResourceURLSchemeHandler ( )
@@ -24,19 +27,45 @@ final class KirieManager: NSObject {
2427 }
2528
2629 func createWebView( initialURL: String ? ) {
27- logInfo ( " createWebView initialURL= \( initialURL ?? " <nil> " ) " )
30+ createWebView ( initialURL: initialURL, remainingHostWindowAttempts: Self . maxHostWindowResolveAttempts)
31+ }
32+
33+ private func createWebView( initialURL: String ? , remainingHostWindowAttempts: Int ) {
34+ logInfo (
35+ " createWebView initialURL= \( initialURL ?? " <nil> " ) "
36+ + " remainingHostWindowAttempts= \( remainingHostWindowAttempts) "
37+ )
2838
2939 guard let hostWindow = resolveHostWindow ( ) else {
40+ if remainingHostWindowAttempts > 0 {
41+ logInfo ( " No active host window yet; retrying WebView creation " )
42+ DispatchQueue . main. asyncAfter ( deadline: . now( ) + Self. hostWindowRetryDelay) { [ weak self] in
43+ self ? . createWebView (
44+ initialURL: initialURL,
45+ remainingHostWindowAttempts: remainingHostWindowAttempts - 1
46+ )
47+ }
48+ return
49+ }
50+
3051 emitIpcError ( " Cannot create WebView because no host window was found " )
3152 return
3253 }
3354
3455 let containerView = ensureContainerView ( attachedTo: hostWindow)
3556 let webView = ensureWebView ( attachedTo: containerView)
36- emitWebViewReady ( )
57+ hostWindow. layoutIfNeeded ( )
58+
59+ DispatchQueue . main. async { [ weak self, weak webView] in
60+ guard let self, let webView, webView === self . webView else {
61+ return
62+ }
3763
38- if let initialURL, !initialURL. isEmpty {
39- load ( initialURL, in: webView)
64+ self . emitWebViewReady ( )
65+
66+ if let initialURL, !initialURL. isEmpty {
67+ self . load ( initialURL, in: webView)
68+ }
4069 }
4170 }
4271
@@ -200,9 +229,7 @@ final class KirieManager: NSObject {
200229 private func resolveHostWindow( ) -> UIWindow ? {
201230 let activeScenes = UIApplication . shared. connectedScenes
202231 . compactMap { $0 as? UIWindowScene }
203- . filter { scene in
204- scene. activationState == . foregroundActive || scene. activationState == . foregroundInactive
205- }
232+ . filter { $0. activationState == . foregroundActive }
206233
207234 for scene in activeScenes {
208235 if let keyWindow = scene. windows. first ( where: \. isKeyWindow) {
0 commit comments