gpt4 book ai didi

ios - 在 CocoaPods 中使用资源包

转载 作者:搜寻专家 更新时间:2023-11-01 06:13:16 24 4
gpt4 key购买 nike

我正在制作一个 pod (MySDK),并希望从 CocoaPods 生成的单独资源包中加载 Assets 。

但是,我无法让它工作。

这是我尝试加载 Storyboard的方式:

let storyBoard = UIStoryboard(name: "SDK", bundle: Bundle(identifier:"org.cocoapods.SchedJoulesSDK"))

这给出了错误:

'Could not find a storyboard named 'SDK' in bundle

bundle 添加到 Xcode 中:

我的 podspec 看起来像这样:

  s.resource_bundles = {
'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}']
}

有什么想法吗?

最佳答案

如果您使用 resourceresources在 CocoaPods PodSpec 文件中,您告诉 Cocoapods 这些是您的库将在运行时加载的资源文件。

如果你的库是作为一个动态框架构建的,这些文件只是复制到该框架的资源文件夹路径,一切都会好起来的。然而,如果您的库是作为静态库构建的,这些库将被复制到主应用程序包 (.app) 的资源文件夹中,这可能是一个问题,因为该主应用程序可能已经有一个资源该名称或另一个 Pod 可能具有该名称的资源,在这种情况下,这些文件将相互覆盖。 Pod 是构建为动态框架还是静态库,不是由 PodSpec 指定的,而是由集成 Pod 的应用程序在 Podfile 中指定的。

因此对于有资源的Pod,强烈推荐使用resource_bundles相反!

在你的例子中,行

s.resource_bundles = {
'MySDK' => ['SDK/*/*.{xib,storyboard,xcassets}'] }

告诉 CocoaPods 创建一个名为 MySDK (MySDK.bundle) 的资源包,并将所有匹配该模式的文件放入该资源包中。如果您的 Pod 是作为框架构建的,则此包位于您的框架包的资源文件夹中;如果它是作为静态库构建的,bundle 会被复制到主应用程序 bundle 的资源文件夹中,如果您将 bundle 命名为与 Pod 相同的方式,这应该是安全的(您不应该将其命名为“MySDK”,而不是“SchedJoulesSDK”)。

这个 bundle 将具有与您的 Pod 相同的标识符,但是当构建动态框架时,您的框架 bundle 也将具有该标识符,然后它是未定义的行为当您通过标识符加载它时正在加载哪个 bundle(目前是外包总是在我的测试中获胜)。

正确的代码应该是这样的(虽然没有测试):

// 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)

因为 resourceBundle 不能在运行时改变,所以只创建它一次(例如在应用程序启动时或当你的框架被初始化时)并将它存储到一个全局变量(或全局类属性)中是安全的,因此您可以在需要时始终使用它(bundle 对象也几乎不使用任何 RAM 内存,因为它只封装元数据):

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
}()
}

该属性是惰性初始化的(这是 static let 属性的默认值,不需要 lazy 关键字)并且系统确保这种情况只发生一次,作为 let 属性一旦初始化就不能改变。请注意,您不能在该上下文中使用 Self.self,您需要使用实际的类名。

在您的代码中,您现在可以在任何需要的地方使用该包:

let storyBoard = UIStoryboard(name: "SDK", 
bundle: SchedJoulesSDK.resourceBundle)

关于ios - 在 CocoaPods 中使用资源包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50625036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com