Search code examples
iosswifttoday-extension

How to hide Today widget on app first run?


I'm wondering how to hide a Today widget on the app's first run.

I don't want to hide it from application(_:didFinishLaunchingWithOptions:) but rather from the widget's info.plist or lifecycle methods in order to decouple the AppDelegate from widget logic.

Does anyone have any idea how to do this?


Solution

  • From 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.

    What you could do is to do the following:

    Check by NSUserDefaults if it´s the first time the app is running and in the set setHasContent:forWidgetWithBundleIdentifier to false. Code example below:

    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")
    }