捆绑iOS框架的路径 [英] Path to bundle of iOS framework

查看:62
本文介绍了捆绑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?

编辑:代码

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

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)

更新:

或搜索通过标识符(框架捆绑包ID)进行捆绑:

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

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

这篇关于捆绑iOS框架的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆