1

I have created a Swift framework and I'm trying to make it into a CocoaPod.

These are all the files in the framework.

enter image description here

I add all the source files plus the .json file in the podspec like so.

spec.source_files = "CountryPicker"
spec.resource  = "CountryPicker/countries.json" 

The files do get added.

enter image description here

Or so it seems. Because when I try to load the json file within the framework code like this

let path = Bundle(for: Self.self).path(forResource: "countries", ofType: "json")!

it keeps failing because it's returning nil every time.

I tried all the methods described here but it's not having any effect. Any idea what I'm doing wrong here?

Isuru
  • 30,617
  • 60
  • 187
  • 303

2 Answers2

4

I am able to do this for other assets, assume it will be the same for you.

First, find the name of your Pod's bundle. I have redacted a lot of this, but if you follow the arrows, you can see how to get it via Xcode.

enter image description here

The order would be:

  1. Select the Pods project
  2. Select the target associated with your pod
  3. With General selected, locate the Bundle Identifier

Once you have that, you can then instantiate the Bundle:

let yourPodBundle = Bundle(identifier: "org.cocoapods.your_pod_sname_here")

Now, pull it all together

let path = yourPodBundle?.path(forResource: "countries", ofType: "json")!
CodeBender
  • 35,668
  • 12
  • 125
  • 132
  • I decided to redo the creation of CocoaPod part via the `pod lib create` command and give it a go. I'll try this out once I get to that part and get back to you :) Thanks. – Isuru Jun 30 '20 at 16:57
  • Isuru did you get this to work? – Ackman Nov 10 '22 at 17:52
0

I suggest you to create a resource bundle and take your resources from there. You need to specify a bundle in resource_bundles in your podspec, then in code get framework bundle, then that resource bundle.

In podspec file:

spec.resource_bundles = {
   'bundle_name' => ['<path to your resources>'],
}

In your Swift code:

let bundle = Bundle(for: <class from framework>.self)
let resourceBundle = Bundle(url: bundle.url(forResource: "bundle_name", withExtension: "bundle")!)! // bundle_name is bundle name from your Podspec file

// get your countries json
resourceBundle.url(forResource: "countries", withExtension: "json")

You can also use this bundle to get images, example:

Image("testImage", bundle: resourceBundle)
mrpaw69
  • 155
  • 9