iOS框架捆绑包的路径

m528fe3b  于 2022-12-15  发布在  iOS
关注(0)|答案(5)|浏览(136)

我正在为iOS开发一个框架,它附带了一些数据文件。为了将它们加载到Dictionary中,我做了如下操作:

public func loadPListFromBundle(filename: String, type: String) -> [String : AnyObject]? {
    guard
       let bundle = Bundle(for: "com.myframework")
       let path = bundle.main.path(forResource: filename, ofType: type),
       let plistDict = NSDictionary(contentsOfFile: path) as? [String : AnyObject]
    else { 
       print("plist not found")
       return nil 
    }

    return plistDict
}

如果我在有框架的操场上使用这个,它就能按预期工作。
但是如果我使用嵌入在应用程序中的框架,它就不再工作了,“路径”现在指向应用程序的捆绑包,而不是框架的捆绑包。
我如何确保框架的包被访问?

**EDIT:**以上代码位于框架中,而不是应用程序中。
**EDIT2:**上面的代码是一个实用函数,不是结构或类的一部分。

tag5nh1u

tag5nh1u1#

使用Bundle(for:Type)

let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: filename, ofType: type)

或者按identifier(框架包ID)搜索包:

let bundle = Bundle(identifier: "com.myframework")
bweufnob

bweufnob2#

雨燕5

let bundle = Bundle(for: Self.self)
let path = bundle.path(forResource: "filename", ofType: ".plist")
ht4b089n

ht4b089n3#

尝试以下代码以获取自定义捆绑包:

let bundlePath = Bundle.main.path(forResource: "CustomBundle", ofType: "bundle")
let resourceBundle = Bundle.init(path: bundlePath!)

更新

如果在您的框架中,请尝试以下操作:

[[NSBundle bundleForClass:[YourClass class]] URLForResource:@"YourResourceName" withExtension:@".suffixName"];
nmpmafwu

nmpmafwu4#

只需指定资源的类名,下面的函数将为您提供与类关联的Bundle对象,因此,如果类与框架关联,它将提供框架的bundle。

let bundle = Bundle(for: <YourClassName>.self)
bxjv4tth

bxjv4tth5#

import class Foundation.Bundle

private class BundleFinder {}

extension Foundation.Bundle {
    /// Returns the resource bundle associated with the current Swift module.
    static var module: Bundle = {
        let bundleName = "ID3TagEditor_ID3TagEditorTests"

        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: BundleFinder.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 ID3TagEditor_ID3TagEditorTests")
    }()
}

出发地:Source
---更新---
它提供了3种关于如何获得正确的bundle的注解用法,这是非常有用的,特别是当你正在开发自己的框架或使用Cocoapods时。

相关问题