iOS Framework中加载资源失败

Framework 中本地资源加载与我们平时工程中的资源加载是不同的,主要是因为它们的Bundle 不同 。 Framework 是一个独立的 Bundle, 主工程中获取到的 Bundle 不是 Framework 的 Bundle。开发一个framework,里面用到图片,在framework里面使用[NSBundle bundleForClass:[self class]],获取到的一直是app的资源名,始终拿不到图片资源,framework类型可能是static library,把它改成dynamic library,应该就可以了。

  1. Image.bundle 中的图片加载
NSBundle*bundle = [NSBundle bundleForClass:[self class]];
UIImage *image = [UIImage imageNamed:@"Image.bundle/image"  inBundle:bundle compatibleWithTraitCollection:nil];
  1. Images.xcassets 中的图片加载
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
UIImage *image = [UIImage imageNamed:@"image" inBundle:bundle compatibleWithTraitCollection:nil];

最后,加载Framework和bundle中的本地html文件时,如果不显示css和img,不能跳转,说明找不到它们的路径。

// framework中html文件的路径
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
//bundle中html文件的路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"my" ofType:@"bundle"];
NSBundle *myBundle = [NSBundle bundleWithPath:path];
//加载baseURL
NSString *path = [bundle bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:oriStr baseURL:baseURL];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容