2

I am trying to display an image bundle inside a Swift Package.

This code let image = UIImage(named: "image", in: Bundle.module, compatibleWith: nil) works when I use png image. But when I use a svg with the same name (image.svg), the image is nil.

This is how I define the resource folder where I save the image in Package.swift

resources: [
  .process("Resources"),
]
Peacemoon
  • 3,198
  • 4
  • 32
  • 56

2 Answers2

5

Your file or asset can be in a xcassets, add a xcassets to Swift Package then import your asset there then type your resources like this:

resources: [Resource.process("Media.xcassets")]

Which Media.xcassets carry your asset, then use this code in Swift Package:

Image("image", bundle: .module)
ios coder
  • 1
  • 4
  • 31
  • 91
  • This is a surprisingly simple solution that I missed out to try. Thank you for pointing out. I tested it and it works as expected. – Peacemoon Aug 01 '21 at 10:32
  • It won't work (so fare as I can tell) if you're not using SwiftUI and want access to the image. macOS provides a `Bundle.image()` function but iOS/tvOS do not. – PKCLsoft Apr 14 '23 at 03:05
0

I found that by placing the asset catalog under "Resources", and including this in the package descriptor:

    .target(
        name: "AppResources",
        dependencies: [],
        resources: [
            .process("Resources")]
    ),

I could then use an extension of UIImage to access my assets:

public extension UIImage {
    static func packagedImage(withName name: String) -> UIImage? {            
        guard let result = UIImage(named: "\(name).png", in: Bundle.module, compatibleWith: nil) else {
            return nil
        }

        return result
    }
}
PKCLsoft
  • 1,359
  • 2
  • 26
  • 35
  • No need to append ".png" to the image name. – HangarRash Apr 14 '23 at 03:32
  • In my case there is as the asset names also have ".png". But you are right than depending on the situation it may not be needed. – PKCLsoft Apr 14 '23 at 07:07
  • My point is that `UIImage(named:)` doesn't need you to specify the image file extension. It will find the image regardless of its actual extension. – HangarRash Apr 14 '23 at 15:09
  • OK. That's news to me. Tests coming up. ...... Testing shows this not to be the case. – PKCLsoft Apr 15 '23 at 03:19
  • Yeah, I guess my memory was faulty. I know you don't need an extension when the image is coming from an image set in an asset. But it does seem to be needed if you are accessing a stand-alone image in the resource bundle. – HangarRash Apr 15 '23 at 03:37