如何先在应用程序上隐藏今日小部件 运行?

How to hide Today widget on app first run?

我想知道如何在应用程序的第一个 运行 上隐藏今日小部件。

我不想从 application(_:didFinishLaunchingWithOptions:) 中隐藏它,而是从小部件的 info.plist 或生命周期方法中隐藏它,以便将 AppDelegate 与小部件逻辑分离。

有人知道怎么做吗?

来自Apples documentation

Typically, a widget appears in the Today view when it has content to display. If a currently running widget no longer has content to display, it can get a widget controller and set to false the flag in the setHasContent:forWidgetWithBundleIdentifier: method.

您可以执行以下操作:

通过 NSUserDefaults 检查应用程序是否是第一次 运行 并且在设置 setHasContent:forWidgetWithBundleIdentifier 中设置为 false。下面的代码示例:

if !NSUserDefaults.standardUserDefaults().boolForKey("firstRun"){
    // first run so do set setHasContent:forWidgetWithBundleIdentifier to false

    // Set your NSUserDefaults firstRun value to false so it does not run again
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstRun")
}