【问题标题】:SwiftUI AppDelegate not working correctlySwiftUI AppDelegate 无法正常工作
【发布时间】:2021-08-22 00:07:54
【问题描述】:

这是我的主文件代码:

import SwiftUI

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        print("Your code here")
        return true
    }
}

@main
struct CouponDeckApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {
            AppContentView()
        }
    }
}

AppDelegate 代码似乎并没有在我每次打开应用程序时都在运行,这是应该的。我不知道是什么导致了这个问题。有谁知道为什么会这样,我应该如何解决?

提前致谢!

附:我在模拟器上运行我的代码,可能问题出在哪里?

编辑:抱歉,也许我不够清楚。我希望代码在您打开应用程序时运行,而不是第一次下载和打开。就像您单击主屏幕上的图标并打开应用程序一样。

【问题讨论】:

  • 您提供的代码按预期工作 - 当应用程序启动时,“您的代码在此处”会打印到控制台。当应用程序从后台转移到前台但实际上并没有再次从头启动时,您是否正在尝试做某事?
  • @jnpdx 是的,基本上只要您点击主屏幕上的应用程序图标并打开它,而不是从头开始下载。
  • 好像需要在willEnterForeground实现代码

标签: ios swiftui appdelegate


【解决方案1】:

你可以试试这个:

class AppDelegate: UIResponder, UIApplicationDelegate {  // <--- here

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        print("\n----------> in here \n")
        return true
    }
}

【讨论】:

  • 在这种情况下UIResponder 有什么变化?
  • 当然可以,但是与这个问题相关的行为会发生什么变化?尤其是因为它不能成为第一响应者,甚至。仅仅说它可以符合其中一些方法并不会改变didFinishLaunchingWithOptions是否被调用,对吗?
  • 顺便说一句,反对票不是我的——我只是不清楚这会发生什么变化
  • 有人不喜欢它,虽然它对我很有效,但可能对谁都不起作用。