支持 iOS 13 SwiftUI 的 Xcode 12 项目:未调用 SceneDelegate 函数

如何解决支持 iOS 13 SwiftUI 的 Xcode 12 项目:未调用 SceneDelegate 函数

我在 Xcode 12 中创建了一个项目,将 iOS 14 作为部署目标(更大的项目)。一段时间后,我意识到我还必须能够支持 iOS 13 设备。我的项目使用 SwiftUI。

将部署目标简单地更改为 iOS 13 显然不是很直接,因为 Xcode 12 生成的某些代码与 iOS 13 不向后兼容。

所以我基本上需要转换我的基于 Xcode 12 的项目(当前部署目标为 iOS 14.0)以支持 iOS 13

以下是我为项目降级所做的准备工作:

  • 安装 Xcode 11.7,创建支持 SwiftUI 的新项目并确保部署目标是 iOS 13.0。因此我知道 Xcode 认为“iOS 13”方式应该是什么,即使用 AppDelegate 和 SceneDelegate。
  • 运行该应用 - 在我的 iOS 14 设备上运行良好。
  • 打开 Xcode 12,创建支持 SwiftUI 的新项目,将部署目标降低到 iOS 13.0(因为它默认设置为 14.x),构建它,然后出现一堆编译问题(如预期)。

然后对 Xcode 12 项目进行了更改:

  • 注释掉 <project>App.swift 文件中的所有内容。
  • 从上面提到的 Xcode 11.7 生成的项目中添加具有相同内容的 AppDelegate.swift 文件。
  • 从上面提到的 Xcode 11.7 生成的项目中添加具有相同内容的 SceneDelegate.swift 文件。
  • 添加 LaunchScreen.storyboard 文件(因为 Xcode 警告它不存在)。
  • 运行应用。

应用程序运行,但未显示 ContentView 的内容。只是一个黑屏(黑色可能是因为我的设备处于黑暗模式)。此外,您会在下面的代码中注意到,我插入了调试日志,但控制台中只打印了“didFinishLaunchingWithOptions”——也就是说,似乎没有调用场景委托方法。

我(当然)在谷歌上搜索了很多,用 Info.plist 尝试了各种方法,但似乎没有任何帮助。

代码:

AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate {
    
    func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("didFinishLaunchingWithOptions")
        return true
    }
    
    // MARK: UISceneSession Lifecycle
    
    func application(_ application: UIApplication,configurationForConnecting connectingSceneSession: UISceneSession,options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        print("configurationForConnecting")      
    }
    
    func application(_ application: UIApplication,didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        print("didDiscardSceneSessions")
    }
}

SceneDelegate.swift

class SceneDelegate: UIResponder,UIWindowSceneDelegate {
    
    var window: UIWindow?
    
    func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
        print("scene willConnectTo")
        guard let windowScene = scene as? UIWindowScene else { return }
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView())
        self.window = window
        window.makeKeyAndVisible()
    }
    
    func sceneDidDisconnect(_ scene: UIScene) {
        print("sceneDidDisconnect")
    }
    
    func sceneDidBecomeActive(_ scene: UIScene) {
        print("sceneDidBecomeActive")
    }
    
    func sceneWillResignActive(_ scene: UIScene) {
        print("sceneWillResignActive")
    }
    
    func sceneWillEnterForeground(_ scene: UIScene) {
        print("sceneWillEnterForeground")
    }
    
    func sceneDidEnterBackground(_ scene: UIScene) {
        print("sceneDidEnterBackground")
    }
}

ContentView.swift

struct ContentView: View {
    
    var body: some View {
        Text("Hello,world!")
            .foregroundColor(.blue)
            .padding()
            .onAppear {
                print("ContentView")
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

信息.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDisplayName</key>
    <string></string>
    <key>LSApplicationCategoryType</key>
    <string></string>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UIApplicationSceneManifest</key>
    <dict>
        <key>UIApplicationSupportsMultipleScenes</key>
        <false/>
        <key>UISceneConfigurations</key>
        <dict>
            <key>UIWindowSceneSessionRoleApplication</key>
            <array>
                <dict>
                    <key>UISceneConfigurationName</key>
                    <string>Default Configuration</string>
                    <key>UISceneDelegateClassName</key>
                    <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
                </dict>
            </array>
        </dict>
    </dict>
    <key>UIApplicationSupportsIndirectInputEvents</key>
    <true/>
    <key>UILaunchScreen</key>
    <dict/>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>

解决方法

我猜你忘了将场景委托文件添加到应用程序目标。构建和运行时,查看控制台,看看是否有关于找不到场景委托的抱怨。这可以解释这种现象。

,

如果您在实现 SceneDelegate 之前已经使用 SwiftApp 构建了应用程序,只需卸载并重新构建它。然后,您可以解决此问题。

persistentIdentifier 将在应用程序首次启动时由系统生成,用于创建新的 Scene。之后,每个应用程序打开的标识符都相同。所以应用不需要创建新的场景。

这就是为什么 configurationForConnecting 没有被调用而是没有设置 rootview 的原因,所以您的应用碰巧显示黑色窗口。

以下 WWDC19 会议视频(大约 31:40)说明了标识符。
https://developer.apple.com/videos/play/wwdc2019/212/?time=1900

希望它能帮助您解决问题。
谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-