Skip to content

Commit 63897bb

Browse files
committed
fix: cache insets on disk, fall back if RCTKeyWindow is unavailable
1 parent 26fb9bb commit 63897bb

File tree

1 file changed

+36
-15
lines changed

1 file changed

+36
-15
lines changed

ios/RNCSafeAreaContext.mm

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ - (NSDictionary *)constantsToExport
3434
- (NSDictionary *)getConstants
3535
{
3636
__block NSDictionary *constants;
37+
static NSString *const kSafeAreaInitialMetricsKey = @"safe-area-context-initial-window-metrics";
3738

3839
RCTUnsafeExecuteOnMainQueueSync(^{
3940
#if TARGET_OS_IPHONE
@@ -42,7 +43,17 @@ - (NSDictionary *)getConstants
4243
NSWindow *window = RCTKeyWindow();
4344
#endif
4445
if (window == nil) {
45-
constants = @{@"initialWindowMetrics" : [NSNull null]};
46+
// Try to retrieve cached metrics from NSUserDefaults
47+
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
48+
NSDictionary *cachedMetrics = [defaults objectForKey:kSafeAreaInitialMetricsKey];
49+
50+
if (cachedMetrics != nil) {
51+
NSLog(@"RNCSafeAreaContext: using cached initial window metrics from NSUserDefaults");
52+
constants = @{@"initialWindowMetrics" : cachedMetrics};
53+
} else {
54+
NSLog(@"RNCSafeAreaContext: no cached metrics available");
55+
constants = @{@"initialWindowMetrics" : [NSNull null]};
56+
}
4657
return;
4758
}
4859

@@ -52,21 +63,31 @@ - (NSDictionary *)getConstants
5263
NSEdgeInsets safeAreaInsets = NSEdgeInsetsZero;
5364
#endif
5465

66+
NSDictionary *windowMetrics = @{
67+
@"insets" : @{
68+
@"top" : @(safeAreaInsets.top),
69+
@"right" : @(safeAreaInsets.right),
70+
@"bottom" : @(safeAreaInsets.bottom),
71+
@"left" : @(safeAreaInsets.left),
72+
},
73+
@"frame" : @{
74+
@"x" : @(window.frame.origin.x),
75+
@"y" : @(window.frame.origin.y),
76+
@"width" : @(window.frame.size.width),
77+
@"height" : @(window.frame.size.height),
78+
},
79+
};
80+
81+
// Only cache the metrics if they haven't been cached before
82+
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
83+
if ([defaults objectForKey:kSafeAreaInitialMetricsKey] == nil) {
84+
[defaults setObject:windowMetrics forKey:kSafeAreaInitialMetricsKey];
85+
[defaults synchronize]; // Ensure it's persisted immediately
86+
NSLog(@"RNCSafeAreaContext: cached initial window metrics to NSUserDefaults for the first time");
87+
}
88+
5589
constants = @{
56-
@"initialWindowMetrics" : @{
57-
@"insets" : @{
58-
@"top" : @(safeAreaInsets.top),
59-
@"right" : @(safeAreaInsets.right),
60-
@"bottom" : @(safeAreaInsets.bottom),
61-
@"left" : @(safeAreaInsets.left),
62-
},
63-
@"frame" : @{
64-
@"x" : @(window.frame.origin.x),
65-
@"y" : @(window.frame.origin.y),
66-
@"width" : @(window.frame.size.width),
67-
@"height" : @(window.frame.size.height),
68-
},
69-
}
90+
@"initialWindowMetrics" : windowMetrics
7091
};
7192
});
7293

0 commit comments

Comments
 (0)