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β
import UIKit
let image = UIImage(named: "Images/my_icon", in: .module, compatibleWith: nil)
Load 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.