windows API_DEPRECATED("Use UIWindowScene.windows on a relevant window scene instead", ios(2.0, 15.0));
目前使用的获取window的方式只支持到iOS15,所以在项目开发的时候担心之后通过该方法拿到的window有问题,研究了下怎么拿新版的window的办法
if (@available(iOS 15, *)) {
__block UIScene * _Nonnull tmpSc;
[[[UIApplication sharedApplication] connectedScenes] enumerateObjectsUsingBlock:^(UIScene * _Nonnull obj, BOOL * _Nonnull stop) {
if ([[UIApplication sharedApplication] connectedScenes].count == 1) {//只有一个的情况下,直接返回
tmpSc = obj;
*stop = YES;
}
if (obj.activationState == UISceneActivationStateForegroundActive) {
tmpSc = obj;
*stop = YES;
}
}];
UIWindowScene *curWinSc = (UIWindowScene *)tmpSc;
[curWinSc.keyWindow addSubview:self.bgView];
} else {
[[[[UIApplication sharedApplication] windows] objectAtIndex:0] addSubview:self.bgView];
}
- 如果拿不到window,可以尝试改下activationState的状态。
+ (UIWindow *)currentWindow {
if (@available(iOS 15, *)) {
__block UIScene * _Nonnull tmpSc;
[[[UIApplication sharedApplication] connectedScenes] enumerateObjectsUsingBlock:^(UIScene * _Nonnull obj, BOOL * _Nonnull stop) {
if (obj.activationState == UISceneActivationStateForegroundActive || obj.activationState == UISceneActivationStateForegroundInactive) {
tmpSc = obj;
*stop = YES;
}
}];
UIWindowScene *curWinSc = (UIWindowScene *)tmpSc;
return curWinSc.keyWindow;
} else {
return [[[UIApplication sharedApplication] windows] objectAtIndex:0];
}
}