私有函数 didFinishLaunchingWithOptions 没有被调用? (Swift 3)

Private func didFinishLaunchingWithOptions not being called? (Swift 3)

难道 didFinishLaunchingWithOptions 不应该在应用 运行ning 第一次启动时被调用吗?我在这个方法上设置了一个断点,当我 运行 模拟器中的应用程序时,断点没有被击中,这意味着该方法没有被调用。每当应用程序启动时,我都试图从 UserDefaults 加载一些数据,但它被完全忽略了。我注意到的一件事是默认情况下它是 private func 而不是 func。如果我去掉 private,我会收到 "there's an almost similar optional requirement in the UIApplicationDelegate" 的警告。有人可以向我解释这意味着什么以及 private func 是否与被忽略的方法有任何关系吗?当我在模拟器中 运行 我的应用程序时,甚至应该调用该方法吗?如果没有,我如何测试在我的应用程序启动后是否正在检索数据? AppDelegate 中的所有其他方法都可以正常调用(例如,applicationDidEnterBackground 方法工作得很好)。

您是否在您的 ViewControllers 之一中实现了 didFinishLaunchingWithOptions?不会调用此方法的自定义实现。此方法在 ApplicationDelegate 中定义,一旦应用程序启动,它将始终被调用。如果您没有在任何 ViewController 中再次定义该方法并且未调用 AppDelegate 中的方法,请尝试重置模拟器。从模拟器菜单 Simulator -> Reset content and settings.

如果编译器提示将 didFinishLaunchingWithOptions 方法设为私有,则该方法的参数可能会导致错误。 application(_:didFinishLaunchingWithOptions:) 委托方法的参数现在桥接到 Swift 作为 [UIApplicationLaunchOptionsKey: Any]?,而不是 [NSObject : AnyObject]?。所以修改方法签名,如图所示。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// ...
}

此方法定义在 ApplicationDelegate 中,应用启动后将始终被调用。如果您没有在任何 ViewController 中再次定义该方法并且未调用 AppDelegate 中的方法,请尝试重置模拟器。

打开模拟器 -> 菜单模拟器 -> 重置内容和设置。

-(BOOL)application(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//..
}

删除您的方法签名并Xcode自动完成它

我还遇到了 AppDelegate 中的 didFinishLaunchingWithOptions 方法不会被调用的问题。我的功能也被标记为私有,看起来像这样

private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool

问题是这是旧语法!显然对我来说,当我将我的项目从 Swift 2.x 转换为 Swift 3 Xcode 时,没有转换 AppDelegate 中的方法。新语法如下所示

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool

Swift 4.2:

func application( _ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool

for Swift ~3.0 Replace didFinishLaunchingWithOptions with follwing signature

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
}

Swift4.2 的更新:

func application(
    _ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool

从设备中删除应用程序并重新启动Xcode 这里对我有用