Home > database >  Problem loading JSON resource in SWIFT package
Problem loading JSON resource in SWIFT package

Time:08-25

I am trying to load a JSON file that is bundled with a Swift package I am working on.

The JSON file is called config.json and it is located in my project under /Sources/<Target>/data/config.json

I am trying to load it using the following code:

guard let sourcesURL = Bundle.main.url(forResource: "config", withExtension: "json") else {
    fatalError("Could not find config.json")
}

... but I keep getting nil. Has anyone had an issue like this? Any idea what I'm doing wrong?

CodePudding user response:

You need to load it with package identifier

guard let sourcesURL = Bundle(identifier: "com.package.name")?.url(forResource: "config", withExtension: "json") else {
  fatalError("Could not find config.json")
}

CodePudding user response:

You should use module

Bundle.module.url(forResource: "config", withExtension: "json")

And you need to make sure the file is included when building by adding below to your target in Package.swift

resources: [
    .copy("data/config.json"). //This could alo be .process
])
  • Related