Skip to main content

iOS - Resources in Module

Swift packages support bundling and accessing resources such as images, JSON files, and localized strings. This guide explains how to configure resources in your q2-demo-ios module using Swift Package Manager and how to access them at runtime using the module bundle.


πŸ—‚ Project Structure​

Your module should be structured to isolate resources within a dedicated Resources folder under the source target directory:

q2-demo-ios/
β”œβ”€β”€ Package.swift
β”œβ”€β”€ q2-demo-ios/
β”‚ β”œβ”€β”€ Sources/
β”‚ β”‚ └── Q2Demo/
β”‚ β”‚ β”œβ”€β”€ Resources/ # <– Resource folder
β”‚ β”‚ β”‚ β”œβ”€β”€ Images/
β”‚ β”‚ β”‚ └── Localization/
β”‚ β”‚ β”œβ”€β”€ Public/
β”‚ β”‚ β”‚ └── Q2DemoModule.swift
β”‚ β”‚ └── Private/
β”‚ β”‚ └── SomePrivateFile.swift

βš™οΈ Configuring Package.swift to Process Resources​

The Package.swift manifest must explicitly declare the Resources directory so that Swift Package Manager processes it into the module bundle.

.target(
name: "q2-demo-ios",
dependencies: [
// Add any dependencies here
],
path: "q2-demo-ios/Sources/Q2Demo",
resources: [
.process("Resources") // Tells SwiftPM to bundle resources
]
)

This will compile all files within the Resources folder and make them available through the module’s resource bundle.

βΈ»

πŸ“¦ Loading Resources Using the Module Bundle​

Swift packages expose their resources via a synthesized Bundle.module. You can use it to safely load any bundled assets within your module code.

Load an Image​

Load an Image
import UIKit
let image = UIImage(named: "Images/my_icon", in: .module, compatibleWith: nil)

Load JSON File​

LLoad JSON File
if let url = Bundle.module.url(forResource: "data", withExtension: "json") {
let data = try Data(contentsOf: url)
// Use your JSON data
}

βœ… Best Practices​

  • Keep resource files organized by type (e.g., Images, Localization, Data).
  • Use .process("Resources") in Package.swift to enable runtime access.
  • Always use Bundle.module to access resources inside Swift packages.
  • For localization, ensure .lproj folders (e.g., en.lproj, fr.lproj) are placed directly inside Resources.

πŸ”— Related Topics

➑️ Once your resources are configured, you can move on to Configuring settings.json to declare your module in the app runtime.