storyboardbundleswift-package-manager

Swift Package Manager - Storyboard bundle


I'm trying to add support for SPM in one of our projects that has storyboards.

Currently we grab it UIStoryboard(name: String, bundle: String?) but this doesn't seem to work with SPM, as there isn't really a bundle. Even printing all the bundles doesn't show the bundle of our package.

Any way we can support storyboards or are SPM's meant to be just files?

Attempts:

UIStoryboard(name: "GiftCards", bundle: Bundle(for: self))
UIStoryboard(name: "GiftCards", bundle: Bundle(for: type(of: self)))
UIStoryboard(name: "GiftCards", bundle: Bundle(identifier: "com.x.x"))

Solution

  • the key thing is to use Bundle.module when instantiating the storyboard

    1- Add this view controller extension to the swift package:

     public extension UIViewController{
            
            public static func getStoryboardVC() -> UIViewController { 
                let storyboard = UIStoryboard(name: String(describing: self), bundle: Bundle.module) // Use Bundle.module
                return storyboard.instantiateInitialViewController()!
            }
     }
    

    The Bundle.module represents the containing package.

    2- In the app, in my case the swift package is called MySwiftPackage. I call that extension method from the swift package to instantiate the view controller I want to present:

       @IBAction func openCard(){
            let vc = MySwiftPackage.MyViewController.getStoryboardVC() as! MySwiftPackage.MyViewController
            vc.personNo = "11111"
            vc.personId = "8888888"
            present(vc, animated: true, completion: nil)
        }