swift - 在 Swift 中终止应用程序时调用函数

标签 swift sprite-kit

当我的应用程序被用户终止时,我如何调用 SKScene 类中的函数?

我需要修改一个值并在应用程序终止时将其保存到 NSUserDefauts。

最佳答案

您可以注册以在您的应用程序即将终止时接收通知。为此,通过

将观察者添加到默认通知中心

swift 5:

 NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: UIApplication.willTerminateNotification, object: nil)

swift 3/4:

// Add this to didMoveToView in your SKScene subclass
NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)

将以下方法添加到您的 SKScene 子类中。该方法将在应用程序终止之前被调用。必须通过添加 @objc 将其“公开”给 Objective-C,以便通知程序可以使用 #selector()

@objc func saveData(notification:NSNotification) {
    // Save your data here
    print("Saving data...")
}

关于swift - 在 Swift 中终止应用程序时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010431/

相关文章:

ios - SpriteKit 中的过渡不工作

json - 如何使用 Core Data 保存 JSON 响应,在 Swift 3 中互联网离线时显示数据?

ios - 水平 UIScrollView 未将当前页面居中

ios - 在没有窗口的情况下访问 PresentedViewController

ios - 为什么我的图像有时无法在模拟器中显示?

sprite-kit - 在 SpriteKit 中使用 SKEmitterNode 和粒子创建轨迹

ios - 在 Sprite Kit 中检测长触摸

ios - UIAlertcontroller 设置属性消息

ios - 允许用户删除文本字段文本但限制最大文本长度

ios - 在 iOS 上的 SpriteKit 中,缩放带纹理的 Sprite 会产生不正确的帧?