How to include assets / resources in a Swift Package Manager library?

后端 未结 6 819
挽巷
挽巷 2020-12-15 15:35

I would like to ship my library using Apple\'s Swift Package Manager. However my lib includes a .bundle file with several strings translated in different languages. Using co

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 15:48

    Due to framework bundles not being supported yet, the only way to provide bundle assets with an SPM target is through a Bundle. If you implement code in your framework to search for a particular bundle in your main project (supporting asset bundles), you can load resources from said bundle.

    Example:

    Access the bundled resources:

    extension Bundle {
        static func myResourceBundle() throws -> Bundle {
            let bundles = Bundle.allBundles
            let bundlePaths = bundles.compactMap { $0.resourceURL?.appendingPathComponent("MyAssetBundle", isDirectory: false).appendingPathExtension("bundle") }
    
            guard let bundle = bundlePaths.compactMap({ Bundle(url: $0) }).first else {
                throw NSError(domain: "com.myframework", code: 404, userInfo: [NSLocalizedDescriptionKey: "Missing resource bundle"])
            }
            return bundle
        }
    }
    

    Utilize the Bundled resources:

            let bundle = try! Bundle.myResourceBundle()
            return UIColor(named: "myColor", in: bundle, compatibleWith: nil)!
    

    You can apply the same logic for all resource files, including but not limited to storyboards, xibs, images, colors, data blobs, and files of various extensions (json, txt, etc).

    Note: Sometimes this makes sense, sometimes it doesn't. Determine use to own project's discretion. It would take very specific scenarios to justify separating Storyboards/Xibs into bundled assets.

提交回复
热议问题