【问题标题】:How to load resources from external framework如何从外部框架加载资源
【发布时间】:2012-08-01 23:52:57
【问题描述】:

我已经构建了一个外部框架,我正在尝试利用框架资源目录中的一些图像。该框架并未在应用程序中复制,而只是对其进行引用。如何从 xyz.framework 资源文件夹中相应地使用 UIImage?

谢谢

【问题讨论】:

    标签: iphone objective-c ios cocoa ipad


    【解决方案1】:

    您需要做的是为框架加载包,然后使用 NSBundle 对象访问资源。

    例如,如果有一个框架定义了一个类“FrameworkClass”,我们可以这样做:

    NSBundle *frameworkBundle = [NSBundle bundleForClass:[FrameworkClass class]];
    NSString *resourcePath = [frameworkBundle pathForResource:@"an_image" ofType:@"jpeg"];
    UIImage *image = [UIImage imageWithContentsOfFile:resourcePath];
    

    这或多或少应该是你想要的。

    【讨论】:

    • 同意@PsychoDad,接受的答案对我不起作用 b/c [NSBundle mainBundle] 从框架代码调用时返回 nil。
    【解决方案2】:

    您可以参考以下框架资源:

    [[NSBundle mainBundle] pathForResource:@"FI.framework/Resources/FileName"
                                    ofType:@"fileExtension"];
    

    注意,这里的 FI 是你的框架名称。

    参考。链接:http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/

    【讨论】:

    • 我没有在项目中复制框架,而是引用了它,即使没有它也能工作吗?框架是否在编译时添加到包中?只是好奇。
    • 在创建框架时,一旦您引用它,它将成为您捆绑包的一部分。因此,在构建框架期间,所有链接的资源都将包含在框架中。
    • DShah,感谢您清除它。我没有在出现问题的资源中引用框架,现在问题得到了解决。谢谢。
    • 这在大多数情况下都不起作用。它还取决于应用项目根文件夹中的 FI.framework 位置。
    • 嗨,我的疑问是,在我的框架中。框架类本身使用一些资源,如 xibs 和图像。我如何从框架内引用它?还有一个疑问......我的可执行文件本身有50mb大小,如果我添加框架来复制资源,应用程序大小会增加那么多吗?
    【解决方案3】:

    斯威夫特 3:

    let bundle = Bundle(for: SomeFrameworkClass.self as AnyClass)
    
    if let path = bundle.path(forResource: "test", ofType: "png") {
        if let image = UIImage(contentsOfFile: path) {
            // do stuff
        }
    }
    

    【讨论】:

      【解决方案4】:

      斯威夫特 4/5:

      let bundle = Bundle(for: type(of: self))
      // let bundle = Bundle(for: ClassOfInterest.self)) // or by pointing to class of interest
      let path = bundle.path(forResource: "filename", ofType: "json")!
      let url = URL(fileURLWithPath: path)
      let data = try! Data(contentsOf: url)
      

      这是来自框架/单元测试内部,在生产代码中你不想强制尝试和强制解包。

      【讨论】:

      • 重要提示:确保指向class,而不是struct。
      【解决方案5】:

      使用包标识符来定位您的框架。

      这要求框架的“MACH-O 类型”为“动态库”并配置为“嵌入和签名”。

      NSBundle *bundle = [NSBundle bundleWithIdentifier:@"com.example.App.ExampleFramework"];
      NSURL *url = [URLForResource:@"resource" withExtension:@"txt"];
      // load the contents with this file url
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 1970-01-01
        • 2014-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多