类型 'UIApplication' 没有成员 'didBecomeActiveNotification'

Type 'UIApplication' has no member 'didBecomeActiveNotification'

我正在尝试使用以下代码为 UIApplication.didBecomeActiveNotification 添加观察者:

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { _ in /* some code */ }

但是 Xcode 说 Type 'UIApplication' has no member 'didBecomeActiveNotification' 尽管它是 officially documented 作为 UIApplication class 常量。我做错了什么?

您应该将通知名称更改为 .UIApplicationDidBecomeActive,如下所示:

NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: nil) { _ in /* some code */ }

显然,didBecomeActiveNotification 仅适用于 iOS 12 SDK。

当您使用Xcode 10时,在构建设置中,如果您设置Swift语言版本要成为 Swift 4,您应该写成:

NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: nil) { _ in /* some code */ }

如果设置为Swift 4.2,请改用:

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { _ in /* some code */ }