swiftuiwidgetkitios17

is there a way to provide iOS version check inside widget extension


I tried to add iOS 17 version check inside WidgetBundle but the widget extension keep on crashing .

Getting Thread 1: Swift runtime failure: Unexpectedly found nil while unwrapping an Optional value. After removing the iOS 17 check it works fine.

Is there any way to provide version check inside widgetBundle?

 struct MyWidgets: WidgetBundle {
        @WidgetBundleBuilder
        var body: some Widget {
            widget1()
            widget2()

            if #available(iOSApplicationExtension 16.1, *) {
               LiveActivity()
            }
            if #available(iOSApplicationExtension 17.0, *) {
               ContactdWidget()
            }
            
        }
}

Solution

  • I had the same problem today. This is my solution

    import WidgetKit
    import SwiftUI
    
    @main
    struct WidgetLauncher {
        // Combine widgets in this way to prevent crashes.
        static func main() {
            if #available(iOSApplicationExtension 17.0, *) {
                WidgetsBundle17.main()
            } else {
                WidgetsBundle16.main()
            }
        }
    }
    
    
    struct WidgetsBundle16: WidgetBundle {
        var body: some Widget {
            SomeWidget()
        }
    }
    
    @available(iOSApplicationExtension 17.0, *)
    struct WidgetsBundle17: WidgetBundle {
        var body: some Widget {
            SomeWidget()
            Only17Widget()
        }
    }