我编写了一个包含 “media.xcassests” 文件的包,媒体文件包含一些图像。 我可以使用以下代码使用 SPM(Swift Package Manager) 访问我的图像(从 github 添加包):
UImage(named: "MyImage", in: Bundle.module, compatibleWith: nil)
当我使用 .podspec 文件将存储库添加到“Pod Lib”(https://cocoapods.org/)时
“Bundle.module” 语法会导致使用以下命令进行 pod 验证时出错:
> pod lib lint
我将其更改为以下代码,问题解决了:
UImage(named: "MyImage", in: Bundle(for: MyClass.self), compatibleWith: nil)
但是SPM无法加载图像
我认为 Bundle 定义导致了这个问题
package.swift 文件有
resources: [.process("Resources")]
我尝试更改一些捆绑包定义,就像此链接中的所有定义一样:
如何在cocoapods中加载资源resource_bundle
我也使用下面的代码,但问题没有解决:
let podBundle = Bundle(for: ImageHelper.self)
if let url = podBundle.url(forResource: "ForceUpdateKit", withExtension: "bundle") {
let bundle = Bundle(url: url)
return UIImage(named: name, in: bundle, compatibleWith: nil)
}
但问题仍然存在。
最后,当我使用“Bundle.module”中的SPM工作而POD不工作,当我使用“Bundle(for:MyClass.self)”时POD工作而SPM不工作。
我找到了2个解决方案:
解决方案1:
class ImageHelper {
static var resolvedBundle: Bundle {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: self)
#endif
}
static func image(_ name: String) -> UIImage? {
return UIImage(named: name,
in: resolvedBundle,
compatibleWith: nil)
}
}
解决方案2:
class ImageHelper {
static func image(_ name: String) -> UIImage? {
let podBundle = Bundle(for: ImageHelper.self)
if let url = podBundle.url(forResource: "YourPackageName_YourPackageName", withExtension: "bundle") {
let bundle = Bundle(url: url)
return UIImage(named: name, in: bundle, compatibleWith: nil)
} else {
return UIImage(named: name,
in: Bundle(for: ImageHelper.self),
compatibleWith: nil)
}
}
}
您可以找到您的资源名称或捆绑包名称:当您转到 Bundle.module 的定义时(您应该构建一次您的项目),您可以看到捆绑包名称,如下所示:“YourPackageName_YourPackageName”,它会转到“resource_bundle_accessor”文件