ios 在CocoaPod框架中引用bundle失败

5us2dqdw  于 2023-06-25  发布在  iOS
关注(0)|答案(2)|浏览(173)

我已经创建了一个Swift框架,并试图将其变成一个CocoaPod。
这些是框架中的所有文件。

我在podspec中添加了所有的源文件和.json文件,这样。

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

文件会被添加。

至少看起来是这样。因为当我尝试像这样在框架代码中加载JSON文件时

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

它一直失败,因为它每次都返回nil。
我尝试了here中描述的所有方法,但没有任何效果。知道我哪里做错了吗

mxg2im7a

mxg2im7a1#

我可以为其他资产这样做,假设它对你也是一样的。
首先,找到Pod的包的名称。我已经编辑了很多,但是如果你按照箭头,你可以看到如何通过Xcode获得它。

顺序如下:
1.选择Pods项目
1.选择与pod关联的目标
1.选中“常规”后,找到捆绑标识符
一旦你有了它,你就可以示例化Bundle了:

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

现在,把这些都集中起来

let path = yourPodBundle?.path(forResource: "countries", ofType: "json")!
im9ewurl

im9ewurl2#

我建议您创建一个资源包,并从中获取您的资源。您需要在podspec中指定resource_bundles中的bundle,然后在代码中获取framework bundle,然后是资源bundle。
在podspec文件中:

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

在Swift代码中:

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

您也可以使用此包获取图像,例如:

Image("testImage", bundle: resourceBundle)

相关问题