I have struggled a lot to how to load resource in cocoapods resource_bundle.
The following is what i put in the .podspecs file.
s.source_files = 'XDCoreLib/Pod/Classes/**/*'
s.resource_bundles = {
'XDCoreLib' => ['XDCoreLib/Pod/Resources/**/*.{png,storyboard}']
}
This is what I am trying to do from the main project.
let bundle = NSBundle(forClass: XDWebViewController.self)
let image = UIImage(named: "ic_arrow_back", inBundle: bundle, compatibleWithTraitCollection: nil)
print(image)
I did see the picture in the XDCoreLib.bundle, but it return a nil.
I struggled with a similar issue for a while. The resource bundle for a pod is actually a separate bundle from where your code lives. Try the following:
Swift 5
let frameworkBundle = Bundle(for: XDWebViewController.self)
let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("XDCoreLib.bundle")
let resourceBundle = Bundle(url: bundleURL!)
let image = UIImage(named: "ic_arrow_back", in: resourceBundle, compatibleWith: nil)
print(image)
-- ORIGINAL ANSWER --
let frameworkBundle = NSBundle(forClass: XDWebViewController.self)
let bundleURL = frameworkBundle.resourceURL?.URLByAppendingPathComponent("XDCoreLib.bundle")
let resourceBundle = NSBundle(URL: bundleURL!)
let image = UIImage(named: "ic_arrow_back", inBundle: resourceBundle, compatibleWithTraitCollection: nil)
print(image)
I don't think any of the other answers have described the relationship to the Podspec. The bundle URL uses the name of the pod and then .bundle to find the resource bundle. This approach works with asset catalogs for accessing pod images both inside and outside of the pod.
Podspec
Pod::Spec.new do |s|
s.name = 'PodName'
s.resource_bundles = {
'ResourceBundleName' => ['path/to/resources/*/**']
}
end
Objective-C
// grab bundle using `Class` in pod source (`self`, in this case)
NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder];
NSURL *bundleURL = [[bundle resourceURL] URLByAppendingPathComponent:#"PodName.bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithURL:bundleURL];
UIImage *podImage = [UIImage imageNamed:#"image_name" inBundle:resourceBundle compatibleWithTraitCollection:nil];
Swift
See this answer.
This will work
In .podspec add s.resources in addition to s.resource_bundles (pod install afterwards)
s.resources = 'XDCoreLib/Pod/Resources/**/*.{png,storyboard}'
Then in your code, its as easy as:
let image = UIImage(named: "image_name.png", in: Bundle(for: type(of: self)), compatibleWith: nil)
Note: You may need to run pod install after updating the .podspec to have the changes to your Xcode proj
You can just check the ID of the Bundle by selecting the Pods project, selecting the desired target, and making sure you're on the General tab.
Then in code you can load say an image in that Pod like so:
backgroundImageView.image = UIImage(named: "business_fellas", in: Bundle(identifier: "org.cocoapods.StandardLibrary3-0"), compatibleWith: nil)
Can create an extension to access the framework bundle easier in your framework source code
extension Bundle {
static func getResourcesBundle() -> Bundle? {
let bundle = Bundle(for {your class}.self)
guard let resourcesBundleUrl = bundle.resourceURL?.appendingPathComponent({bundle name}) else {
return nil
}
return Bundle(url: resourcesBundleUrl)
}
}
Just for the record: I wanted to open a NIB from a Category stored in a CocoaPods library. Of course [self classForCoder] gave UIKit back (because of the Category), so the above methods didn't work.
I resolved the issue using some hardcoded paths:
NSURL *bundleURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:#"Frameworks/MyCocoaPodLibraryName.framework"];
NSBundle *podBundle = [NSBundle bundleWithURL:bundleURL];
CustomView *customView = [[podBundle loadNibNamed:#"CustomView" owner:self options:nil] firstObject];
It seems like for some reason **/*.{extensions} pattern is required for this to work I ended up creating my podspec like this
s.resource_bundle = { '<BundleName>' => 'Pod/Resources/**/*.storyboard' }
s.resource = 'Pod/Resources/**/*.storyboard'
even though my actual path is Pod/Resources/.storyboard*
And then to find my bundle I used
#Jhelzer's answer although any way to get bundle e.g. by class or URL or bundleID will work after above setup.
You can also have a look into this answer for more refrences.
Interesting thing is when you need to do it in the source files that are also in the cocoapod library
I faced it when used a xib and plist files in my pod.
That was solved in the next way. Example of loading a xib file:
let bundle = Bundle(for: self.classForCoder)
let viewController = CocoapodViewController(nibName: "CocoapodViewController", bundle: bundle)
import class Foundation.Bundle
private class BundleFinder {}
extension Foundation.Bundle {
/// Returns the resource bundle associated with the current Swift module.
static var module: Bundle = {
let bundleName = "ID3TagEditor_ID3TagEditorTests"
let candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,
// Bundle should be present here when the package is linked into a framework.
Bundle(for: BundleFinder.self).resourceURL,
// For command-line tools.
Bundle.main.bundleURL,
]
for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
return bundle
}
}
fatalError("unable to find bundle named ID3TagEditor_ID3TagEditorTests")
}()
}
From: https://www.fabrizioduroni.it/2020/10/19/swift-package-manager-resources/
For me the following worked because I'm using a static pod.
s.resource_bundle = '<BundleName>' => 'Path to resources'
s.resource = 'Path to resources'
Related
I have a project with some basic functionalities which I can reuse and I am trying to use that as a framework in another project. So my podspec includes strings, swift, assets files and all got added in to the project but the strings keys are not taking the value from localizables.strings. Basically it is not getting from the bundle path. Here is the code where I am calling the strings file inside the framework. "path" is getting as nil. It is working fine in the base project
let bundle: Bundle = .main
if let currentLanguage = languageManager.getCurrentLanguage() {
if let path = bundle.path(forResource: currentLanguage.rawValue, ofType: "lproj"),
let bundle = Bundle(path: path) {
return bundle.localizedString(forKey: self, value: nil, table: nil)
}
}
I fixed the issue.. In podspec, it was
spec.resource_bundle = { 'AppName' => ['AppName/**/*.{strings}'] }
I changed it to
spec.resources = "AppName/**/*.{xcassets}", "AppName/**/*.{Strings}"
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.
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")!
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.
I am making a pod (MySDK) and would like to load the assets from the separate resource bundles CocoaPods generates.
However, I can not get it to work.
Here is how I tried to load the storyboard:
let storyBoard = UIStoryboard(name: "SDK", bundle: Bundle(identifier:"org.cocoapods.SchedJoulesSDK"))
This gives the error:
'Could not find a storyboard named 'SDK' in bundle
The bundle is added in Xcode:
And my podspec looks like this:
s.resource_bundles = {
'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}']
}
Any ideas?
If you use resource or resources in a CocoaPods PodSpec file, you tell Cocoapods that these are the resource files your library will load during runtime.
If your library is built as a dynamic framework, these files are just copied to the resource folder path of that framework and everything will be fine. Yet if your library is built as a static library, these are copied to the resource folder of the main application bundle (.app) and this can be a problem as this main application may already have a resource of that name or another Pod may have a resource of that name, in that case these files will overwrite each other. And whether a Pod is built as dynamic framework or as a static library is not specified by the PodSpec but in the Podfile by the application integrating your Pod.
Thus for Pods with resources, it is highly recommended to use resource_bundles instead!
In your case, the lines
s.resource_bundles = {
'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}'] }
tell CocoaPods to create a resource bundle named MySDK (MySDK.bundle) and place all files matching the pattern into that resource bundle. If your Pod is built as a framework, this bundle is located in the resources folder of your framework bundle; if it is built as a static library, the bundle is copied to the resources folder of the main application bundle, which should be safe if you name your bundle the same way as your Pod (you should not name it "MySDK", rather "SchedJoulesSDK").
This bundle will have the same identifier as your Pod, however when dynamic frameworks are built, your framework bundle will have that identifier as well and then it's undefined behavior which bundle is being loaded when you load it by identifier (and currently the outer bundle always wins in my tests).
Correct code would look like this (not tested, though):
// Get the bundle containing the binary with the current class.
// If frameworks are used, this is the frameworks bundle (.framework),
// if static libraries are used, this is the main app bundle (.app).
let myBundle = Bundle(for: Self.self)
// Get the URL to the resource bundle within the bundle
// of the current class.
guard let resourceBundleURL = myBundle.url(
forResource: "MySDK", withExtension: "bundle")
else { fatalError("MySDK.bundle not found!") }
// Create a bundle object for the bundle found at that URL.
guard let resourceBundle = Bundle(url: resourceBundleURL)
else { fatalError("Cannot access MySDK.bundle!") }
// Load your resources from this bundle.
let storyBoard = UIStoryboard(name: "SDK", bundle: resourceBundle)
As resourceBundle cannot change at runtime, it is safe to create it only once (e.g. on app start or when your framework is initialized) and store it into a global variable (or global class property), so you have it always around when needed (a bundle object also hardly uses any RAM memory, as it only encapsulates meta data):
final class SchedJoulesSDK {
static let resourceBundle: Bundle = {
let myBundle = Bundle(for: SchedJoulesSDK.self)
guard let resourceBundleURL = myBundle.url(
forResource: "MySDK", withExtension: "bundle")
else { fatalError("MySDK.bundle not found!") }
guard let resourceBundle = Bundle(url: resourceBundleURL)
else { fatalError("Cannot access MySDK.bundle!") }
return resourceBundle
}()
}
The property is initialized lazy (that's default for static let properties, no need for the lazy keyword) and the system ensures that this happen only once, as a let property must not changed once initialized. Note that you cannot use Self.self in that context, you need to use the actual class name.
In your code you can now just use that bundle wherever needed:
let storyBoard = UIStoryboard(name: "SDK",
bundle: SchedJoulesSDK.resourceBundle)
You can use like...
s.resource = "icon.png" //for single file
or
s.resources = "Resources/*.png" //for png file
or
s.resources = "Resources/**/*.{png,storyboard}" //for storyboard and png files
or
s.resource_bundles = {
"<ResourceBundleName>" => ["path/to/resources/*/**"]
}
This is what I ended up with...
import Foundation
public extension Bundle {
public static func resourceBundle(for frameworkClass: AnyClass) -> Bundle {
guard let moduleName = String(reflecting: frameworkClass).components(separatedBy: ".").first else {
fatalError("Couldn't determine module name from class \(frameworkClass)")
}
let frameworkBundle = Bundle(for: frameworkClass)
guard let resourceBundleURL = frameworkBundle.url(forResource: moduleName, withExtension: "bundle"),
let resourceBundle = Bundle(url: resourceBundleURL) else {
fatalError("\(moduleName).bundle not found in \(frameworkBundle)")
}
return resourceBundle
}
}
Example usage...
class MyViewController: UIViewController {
init() {
super.init(nibName: nil, bundle: Bundle.resourceBundle(for: Self.self))
}
}
or
tableView.register(UINib(nibName: Self.loginStatusCellID, bundle: Bundle.resourceBundle(for: Self.self)), forCellReuseIdentifier: Self.loginStatusCellID)
I have the same issue, if I only use the bundle line:
s.resource_bundles = {
'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}']
}
I get a runtime crash when I reference my storyboard. However, if I explicitly add each storyboard as a resource like so:
s.resources = ["Resources/MyStoryboard.storyboard", "Resources/MyStoryboard2.storyboard"]
Everything works fine. I don't think we should have to explicitly add each storyboard as a resource, but I haven't been able to make it work any other way.
One thing you could try is changing you resource bundle reference to recursively search in your folders with the ** nomenclature like this:
s.resource_bundles = {
'MySDK' => ['SDK/**/*.{xib,storyboard,xcassets}']
}
I've developed an iOS framework several months ago, and now I would like to use CocoaPods to develop and distribute it easily. Now I distribute it sending my .framework file, I know this is not the best way and because of that I would like to use CocoaPods.
My problem is, inside my framework I use CoreData and I cannot make it work with Pods.
If I get my old .framework and import it into my app project, everything works nice and CoreData works like a charm.
Digging into the issue, it seems that the Database.momd is not found into the bundle.
I'm going to attach the piece of code inside the framework that fails:
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle bundleWithIdentifier:#"kemmitorz.myFramework"] URLForResource:#"Database" withExtension:#"momd"];
// HERE modelURL RETURNS NIL with Pods
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
I know this could be caused by wrong framework configuration, or wrong Pods configuration, but I don't know what I'm missing.
Also, here is my myFramework.podspec file:
Pod::Spec.new do |s|
s.name = 'myFramework'
s.version = '0.1.0'
s.summary = 'A short description of myFramework.'
....
s.ios.deployment_target = '8.0'
s.source_files = 'myFramework/**/*.{h,m}'
s.frameworks = 'Foundation', 'Security', 'CFNetwork', 'CoreData'
s.library = 'icucore'
s.dependency 'SocketRocket'
s.dependency 'AFNetworking'
s.dependency 'OCMapper'
end
I've also tried to add {h,m,xcdatamodeld} to the type of source files unsuccessfully.
What I'm missing? Repeat, if I compile and import the framework on my own, everything works, so I suppose is something related with CocoaPods configuration.
It depends on the cocoapods version you are using, The recommended way to do it in 1.0.x is to add the s.resource_bundles with a list of resource files that should be included in the bundle Cocoapods resource_bundles, for example:
...
s.source_files = 'myFramework/**/*.{h,m}'
s.resource_bundles = {'myFramework' => ['myFramework/*.xcdatamodeld']}
...
And then use some class of your framework to get the bundle and the resource:
guard let bundleURL = NSBundle(forClass: FrameworkClass.self).URLForResource("myFramework", withExtension: "bundle") else { throw Error }
guard let frameworkBundle = NSBundle(URL: bundleURL) else { throw Error }
guard let momURL = frameworkBundle.URLForResource("Database", withExtension: "momd") else { throw Error }
Things can get a little tricky here, but if you use the right paths everything works as expected.
A little update for swift 5 as I had been struggling to get this to work.
In the podspec I needed to define the s.resource_bundles as
s.resource_bundles = {
'FrameworkNameHere' => ['FrameworkNameHere/**/*.{xcdatamodeld}']
}
and in code to get the managed object model
guard let bundleUrl = Bundle(for: self).url(forResource: "FrameworkName", withExtension: "bundle"),
let frameworkBundle = Bundle(url: bundleUrl),
let modelUrl = frameworkBundle.url(forResource: "CoreDataModelName", withExtension: "momd"),
let managedObjectModel = NSManagedObjectModel(contentsOf: modelUrl) else {
fatalError("Managed object model not found")
}
Although this seems to be failing my unit tests that were originally built explicitly using the frameworks bundle id. I am thinking an initialiser for my core data class that allows me to do one or the other based on unit test/ app environment may be the answer.
I'm trying to get a pathForResource for a plist file, when the file was in the mainBundle it was easy, i used:
let path = NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")
But now i moved the settings file to another bundle and i don't know how to get it. I tried to use forClass and allBundles but i'm a swift rookie and didn't managed to make it work. Also coulden't find the solution over the web. It seems all the NSBundle usages examples is only for mainBundle
If you don't know which bundle has your resource you could loop through all of them:
let bundles = NSBundle.allBundles()
var path : String?
var myBundle : NSBundle?
for bundle in bundles {
if let resourcePath = (bundle as! NSBundle).pathForResource("Settings", ofType: "plist") {
path = resourcePath
myBundle = bundle
break
}
}
On the other hand, if you do have the path or the identifier of your bundle you could use:
let bundle = NSBundle(path: "the-bundle-path")
or
let bundle = NSBundle(identifier: "bundle-identifier")
This has nothing to do with the level of your Swift programming knowledge, rather with the interface NSBundle exposes. You should check the docs out to see if they can help you.