Search code examples
iosswifttoday-extension

iOS - create a today widget extension programmatically


I am trying to create a today widget. I don’t want to use the storyboard.

I follow the instruction on this page. I remove main.storyboard, remove the NSExtensionMainStoryboard key and add the NSExtensionPrincipalClass key, using TodayViewController - name of my view controller for the value.

Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>Today</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>NSExtension</key>
    <dict>
        <key>NSExtensionPrincipalClass</key>
        <string>TodayViewController</string>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.widget-extension</string>
    </dict>
</dict>
</plist>

My app crashes right after launching with the following message.


Terminating app due to uncaught exception 
'NSInvalidArgumentException', 
reason: '*** -[__NSDictionaryM setObject:forKey:]:
 object cannot be nil 
(key: B30E0116-B86D-428B-A5DC-5C7732BEAEC5)'
*** First throw call stack:
(0x18245dc30 0x1821780c8 0x1824b65f4 0x1824c0618 
0x182332a24 0x1827dff7c 
0x1827df644 0x182103bb0 0x18210500c 0x18210b484 
0x18210beb0 0x182114f20 0x18216aaa0 0x182170c78)
libc++abi.dylib: terminating with uncaught exception of type NSException

How to add a toady-widget programmatically - without using main.storyboard?


Solution

  • You can add today-widget without a storyboard. Your .plist file should contain NSExtensionMainStoryboard or NSExtensionPrincipalClass key with a string value in the NSExtension dictionary.

    Just add:

    @objc(TodayViewController)
    class TodayViewController: UIViewController...
    

    and add TodayViewController string name as value with NSExtensionPrincipalClass key in .plist file.