我有一个外部库,应该在其中访问嵌入式资源。这个库应该可以通过SPM和框架(例如直接链接,迦太基或可可波德(访问。
问题是要访问这些资源,当库用作swift包时,我必须调用Bundle.module
,当用作框架时,必须调用Bundle(for:)
。
有没有办法检查我是将库编译为一个swift包还是一个框架,比如预处理器条件?
Bundle.module
将与内部访问级别合成,无论您的包是否包含任何资源。它只有在打开Package.swift
清单文件时才可见,尝试以其他方式访问它会导致错误。Swift软件包管理器不依赖于.xcodeproj
,所以您可以使用它。
Cocoapods,迦太基没有那么喜欢,所以你必须合成你自己的Bundle.module
,这里有一个解决方案。
//
// Bundle+Resource.swift
// DateTimePicker
//
// Created by Duy Tran on 10/9/20.
//
import Foundation
private class MyBundleFinder {}
extension Foundation.Bundle {
/**
The resource bundle associated with the current module..
- important: When `DateTimePicker` is distributed via Swift Package Manager, it will be synthesized automatically in the name of `Bundle.module`.
*/
static var resource: Bundle = {
let moduleName = "DateTimePicker"
#if COCOAPODS
let bundleName = moduleName
#else
let bundleName = "(moduleName)_(moduleName)"
#endif
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: MyBundleFinder.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 (bundleName)")
}()
}
似乎很多开发人员都在寻找解决方案,我将发表一篇Medium文章寻求帮助。