使用 Swift Package Manager 时如何访问包

Tal*_*ion 5 ios cocoapods swift swift-package-manager

我有一个支持CocaPods. 我现在添加了对Swift Package Manager 的支持,但在尝试访问框架的捆绑包时遇到崩溃。

    static func debuggerBundle(from target: AnyClass) -> Bundle {
        let podBundle = Bundle(for:  target)
        guard let bundleURL = podBundle.url(forResource: "Harlow", withExtension: "bundle"),
        let bundle = Bundle(url: bundleURL) else { fatalError("Must have a local bundle") }
        return bundle
    }
Run Code Online (Sandbox Code Playgroud)

使用 进行安装时CocoaPods.ipa会包含一个/Frameworks包含所有框架的文件夹。但是当使用SPM运行时,框架不存在。

使用 CocoaPods

使用 CocoaPods

使用SPM

使用SPM

我们如何使用 SPM 访问框架的捆绑包?

https://github.com/stanwood/Harlow/

ric*_*zza 13

正如评论中提到的,SPM 包版本 5.3 是支持捆绑资源的最低版本。如果您需要维持对 5.1 的支持,您可以添加第二个包文件,其中包括对 5.3 的支持:Package@swift-5.3.swift.

使用 Harlow 存储库作为基础,新的包文件将如下所示:

// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription

let package = Package(
    name: "Harlow",
    platforms: [
        .iOS(.v10)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "Harlow",
            targets: ["Harlow"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(url: "https://github.com/shu223/Pulsator.git", .upToNextMajor(from: "0.6.3")),
        .package(url: "https://github.com/schmidyy/Loaf.git", .upToNextMajor(from: "0.7.0")),
        .package(url: "https://github.com/stanwood/SourceModel_iOS.git", .upToNextMajor(from: "1.3.3"))
    ],
    targets: [
        .target(
            name: "Harlow",
            dependencies: ["Pulsator", "SourceModel", "Loaf"],
            resources: [.copy("Resources")]
        ),
        .testTarget(
            name: "HarlowTests",
            dependencies: ["Harlow"]),
    ],
    swiftLanguageVersions: [.v5]
)
Run Code Online (Sandbox Code Playgroud)

这将使Bundle.module参考变得可用。您可以通过您的扩展提供对此实例的静态引用,Bundle如下所示:

extension Bundle {
    public static var harlow: Bundle = .module
}
Run Code Online (Sandbox Code Playgroud)

完成后,您应该能够使用harlow捆绑包引用来加载您的DefaultSettings.plist. ( Bundle.harlow.url(forResource:withExtension:))