ios开发 加载本地html,iOS Framework 开发资源文件(图片、本地HTML、xib等)加载

自定义开发的 Framework 中本地资源加载与我们平时工程中的资源加载是不同的,主要原因是 Bundle 的不同 。开发的 Framework 是一个独立的 Bundle, 主工程中平时常用的 mainBundle 获取到的 Bundle 不是 Framework 的 Bundle。

注: Bundle 介绍

1. 自定义 Framework 中图片资源加载

1.1 Image.bundle 中的图片加载

NSBundle*bundle = [NSBundle bundleForClass:[self class]];

UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"Image.bundle/%@",image] inBundle:bundle compatibleWithTraitCollection:nil];

注:图片资源在 .bundle 文件中

使用 bundleForClass: 方法获取当前类所在的 bundle。

使用 UIImage 的类方法 + (nullable UIImage *)imageNamed:(NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection;此时 name 参数需要拼接上 image 所在 Image.bundle 的路径;bundle 参数需要传获取的 bundle 对象。

xib、storyboard 中无法使用对应的图片资源。

1.2 Images.xcassets 中的图片加载

NSBundle *bundle = [NSBundle bundleForClass:[self class]];

UIImage *image = [UIImage imageNamed:@"zlife_add_360yt" inBundle:bundle compatibleWithTraitCollection:nil];

注:图片资源在 .xcassets 文件中

1.类方法 + (nullable UIImage *)imageNamed:(NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection; 中的 name 参数直接传入图片名字。

xib、storyboard 中可以使用对应的图片资源。

2. 自定义 Framework 中本地 HTML 资源加载

蓝色的是folder 黄色的是group。二者区别

group:

一般在工程中是文件夹的形式,如果选择 Group 则在本地的目录中会出现对应的文件夹,如果选择 Group without Floder 则本地以散乱的形式放在一起的,除非你是从外部以group的形式引用进来的。

958ad743d19e?appinstall=0

创建Group.png

folder :

只能作为资源,整个引用进项目,不能编译代码,也就是说,以folder形式引用进来的文件,不能被放在complie sources列表里面。

958ad743d19e?appinstall=0

创建Folder.png

2.1 本地 HTML 加载 Group 中的图片

958ad743d19e?appinstall=0

Group项目中目录.png

获取 HTML 文件

NSBundle *bundle = [NSBundle bundleForClass:[self class]];

NSURL *htmlFileURL = [[bundle URLForResource:@"home" withExtension:@"html"];

HTML 文件中加载图片(包括 CSS)资源处的书写应该删除路径,只保留图片名字

wangguan.png

2.2 本地 HTML 加载 folder 中的图片

958ad743d19e?appinstall=0

Folder项目中目录.png

HTML 文件中加载图片(包括 CSS)资源处的书写,应按正常的 HTML 资源路径书写

wangguan.png

3. 自定义 Framework 中 xib 文件等

加载 xib

NSBundle *woHomeBundle = [NSBundle bundleForClass:[WHMainViewController class]];

WHMainViewController *mainVC = [[WHMainViewController alloc] initWithNibName:@"WHMainViewController" bundle:woHomeBundle];

加载音频

NSBundle *bundle = [NSBundle bundleForClass:[self class]];

NSString *soundFilePath = [bundle pathForResource: @"greed" ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值