iOS 框架包的路径

Path to bundle of iOS framework(iOS 框架包的路径)

本文介绍了iOS 框架包的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有一些数据文件的 iOS 框架.要将它们加载到 Dictionary 我会这样做:

I am working on a framework for iOS, which comes with some datafiles. To load them into a Dictionary I do something like this:

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
}

如果我在带有框架的游乐场中使用它,它会按预期工作.

If I use this in a playground with the framework, it works as intended.

但是如果我使用嵌入在应用程序中的框架,它就不再工作了,路径"现在指向应用程序的捆绑包,而不是框架.

But if I use the framework embedded in an app, it doesn't work anymore, the "path" now points to the bundle of the app, not of the framework.

如何确保框架的捆绑包被访问?

How do I make sure that the bundle of the framework is accessed?

上面的代码驻留在框架中,而不是在应用程序中.

the code above resides in the framework, not in the app.

上面的代码是一个实用函数,不是结构或类的一部分.

the code above is a utility function, and is not part of a struct or class.

推荐答案

使用Bundle(for:Type):

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

或通过 identifier(框架包 ID)搜索包:

or search the bundle by identifier (the frameworks bundle ID):

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

这篇关于iOS 框架包的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:iOS 框架包的路径

基础教程推荐