Reputation: 2069
I developed an iOS framework that users can use with CocoaPod. But when using it in a project, there is an error on this line:
let url = Bundle(for: type(of: self)).url(forResource: "file_name", withExtension: "html", subdirectory: "assets")!
This line is in the framework and the error is:
Unexpectedly found nil while unwrapping an Optional value
In the framework, I have a folder named "assets" and a file named "file_name.html". The error happens only when it is used in a framework.
Upvotes: 2
Views: 351
Reputation: 1946
It looks like "file_name.html" is missing in your Cocoapod framework. Please add it something like below in your podspec.
s.resource_bundles = {
'ResourceBundleName' => ['path/to/resources/Assets/*']
}
s.resources = "ResourceBundleName/**/*.{html,icon}"
Your code seems to be absolutely fine when i added it in one of the functions of my sample Framework project. No compilation error.
You can also use following code inside your pod to access the resource.
let frameworkBundle = Bundle(for: self.classForCoder)
let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("FrameworkName.bundle")
let resourceBundle = Bundle(url: bundleURL!)
let url = resourceBundle?.url(forResource: "file_name", withExtension: "html", subdirectory: "assets")!
Please see this link for more info on how to access resource from Framework: "https://useyourloaf.com/blog/loading-resources-from-a-framework/". Thought it will be helpful to you.
Upvotes: 1
Reputation: 6693
let url = Bundle(for: type(of: self)).url(forResource: "file_name", withExtension: "html", subdirectory: "assets")!
-------------------------------^
Make sure that self
points to a class of the framework in order to find the right bundle. And you don't need to use type(of:_)
:
let bundle = Bundle(for: FrameworkClass.self)
let url = bundle.url(forResource: "file_name", withExtension: "html", subdirectory: "assets")!
Upvotes: 1